UNPKG

2.14 kBJavaScriptView Raw
1const Future = require('fluture');
2const { isEmpty, pathOr, pipe } = require('ramda');
3const webpack = require('webpack');
4const DevServer = require('webpack-dev-server');
5const { toArray } = require('./utils');
6
7// errors :: (Error|Array Error err -> Object stats) -> Array Error
8const getErrors = (err, stats) => (err ? toArray(err) : stats.toJson().errors);
9
10// compiler :: Object config -> Future Error Object
11const compiler = pipe(Future.of, Future.ap(Future.of(webpack)));
12
13// compile :: Object config -> Future Error Object
14const compile = pipe(
15 compiler,
16 Future.chain(compiler => Future((reject, resolve) => {
17 compiler.run((err, stats) => {
18 const errors = getErrors(err, stats);
19
20 isEmpty(errors) ? resolve(stats) : reject(errors);
21 });
22 }))
23);
24
25// devServer :: Object config -> Future Error Object
26const devServer = pipe(
27 compiler,
28 Future.map(compiler => Object.assign(new DevServer(compiler, compiler.options.devServer), { compiler }))
29);
30
31// serve :: Object config -> Future Error Object
32const serve = pipe(
33 devServer,
34 Future.chain(server => Future((reject, resolve) => {
35 const { compiler } = server;
36 const { host, port } = compiler.options.devServer;
37
38 server.listen(port, host, () => resolve(compiler));
39 }))
40);
41
42// validator :: Object config -> Future Error Object
43const validator = pipe(Future.of, Future.ap(Future.of(webpack.validate)));
44
45// validate :: Object config -> Future Error Object
46const validate = config => validator(config)
47 .chain(errors => (isEmpty(errors) ?
48 Future.of(config) :
49 Future.reject([new webpack.WebpackOptionsValidationError(errors)])));
50
51// watch :: Object config -> Future Error Object
52const watcher = pipe(
53 compiler,
54 Future.chain(compiler => Future((reject, resolve) => {
55 const watchOptions = pathOr({}, ['options', 'watchOptions'], compiler);
56
57 compiler.watch(watchOptions, (err, stats) => {
58 const errors = getErrors(err, stats);
59
60 isEmpty(errors) ? resolve(compiler) : reject(errors);
61 });
62 }))
63);
64
65module.exports = {
66 getErrors,
67 compiler,
68 compile,
69 devServer,
70 serve,
71 validator,
72 validate,
73 watcher
74};