1 | const Future = require('fluture');
|
2 | const { isEmpty, pathOr, pipe } = require('ramda');
|
3 | const webpack = require('webpack');
|
4 | const DevServer = require('webpack-dev-server');
|
5 | const { toArray } = require('./utils');
|
6 |
|
7 |
|
8 | const getErrors = (err, stats) => (err ? toArray(err) : stats.toJson().errors);
|
9 |
|
10 |
|
11 | const compiler = pipe(Future.of, Future.ap(Future.of(webpack)));
|
12 |
|
13 |
|
14 | const 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 |
|
26 | const devServer = pipe(
|
27 | compiler,
|
28 | Future.map(compiler => Object.assign(new DevServer(compiler, compiler.options.devServer), { compiler }))
|
29 | );
|
30 |
|
31 |
|
32 | const 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 |
|
43 | const validator = pipe(Future.of, Future.ap(Future.of(webpack.validate)));
|
44 |
|
45 |
|
46 | const validate = config => validator(config)
|
47 | .chain(errors => (isEmpty(errors) ?
|
48 | Future.of(config) :
|
49 | Future.reject([new webpack.WebpackOptionsValidationError(errors)])));
|
50 |
|
51 |
|
52 | const 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 |
|
65 | module.exports = {
|
66 | getErrors,
|
67 | compiler,
|
68 | compile,
|
69 | devServer,
|
70 | serve,
|
71 | validator,
|
72 | validate,
|
73 | watcher
|
74 | };
|