1 | 'use strict';
|
2 |
|
3 | const updateNotifier = require('update-notifier');
|
4 | const webpack = require('webpack');
|
5 | const weblog = require('webpack-log');
|
6 | const eventbus = require('./lib/bus');
|
7 | const getOptions = require('./lib/options');
|
8 | const getServer = require('./lib/server');
|
9 | const pkg = require('./package.json');
|
10 |
|
11 | module.exports = (opts) => {
|
12 | updateNotifier({ pkg }).notify();
|
13 |
|
14 | return getOptions(opts)
|
15 | .then((results) => {
|
16 | const { options, configs } = results;
|
17 |
|
18 | options.bus = eventbus(options);
|
19 | const { bus } = options;
|
20 |
|
21 | if (!options.compiler) {
|
22 | for (const config of configs) {
|
23 | if (typeof config.entry === 'string') {
|
24 | config.entry = [config.entry];
|
25 | }
|
26 | }
|
27 |
|
28 | options.compiler = webpack(configs.length > 1 ? configs : configs[0]);
|
29 | }
|
30 |
|
31 | options.compiler.plugin('done', (stats) => {
|
32 | const json = stats.toJson();
|
33 | if (stats.hasErrors()) {
|
34 | bus.emit('compiler-error', json);
|
35 | }
|
36 |
|
37 | if (stats.hasWarnings()) {
|
38 | bus.emit('compiler-warning', json);
|
39 | }
|
40 | });
|
41 |
|
42 | const { close, server, start } = getServer(options);
|
43 |
|
44 | start(options);
|
45 |
|
46 | for (const sig of ['SIGINT', 'SIGTERM']) {
|
47 | process.on(sig, () => {
|
48 | close(() => {
|
49 | const log = weblog({ name: 'serve', id: 'webpack-serve' });
|
50 | log.info(`Process Ended via ${sig}`);
|
51 | server.kill();
|
52 | process.exit(0);
|
53 | });
|
54 | });
|
55 | }
|
56 |
|
57 | return Object.freeze({
|
58 | close,
|
59 | compiler: options.compiler,
|
60 | on(...args) {
|
61 | options.bus.on(...args);
|
62 | }
|
63 | });
|
64 | });
|
65 | };
|