This repository has been archived by the owner on Apr 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
index.js
89 lines (75 loc) · 2.53 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
'use strict';
const updateNotifier = require('update-notifier');
const webpack = require('webpack');
const weblog = require('webpack-log');
const eventbus = require('./lib/bus');
const { timeFix, toArray } = require('./lib/config');
const getOptions = require('./lib/options');
const getServer = require('./lib/server');
const WebpackServeError = require('./lib/WebpackServeError');
const pkg = require('./package.json');
module.exports = (opts) => {
updateNotifier({ pkg }).notify();
return getOptions(opts)
.then((results) => {
const { options, configs } = results;
const log = weblog({ name: 'serve', id: 'webpack-serve' });
options.bus = eventbus(options);
const { bus } = options;
if (!options.compiler) {
for (const config of configs) {
toArray(config);
timeFix(config);
}
try {
options.compiler = webpack(configs.length > 1 ? configs : configs[0]);
} catch (e) {
throw new WebpackServeError(`An error was thrown while initializing Webpack\n ${e.toString()}`);
}
}
// if no context was specified in a config, and no --content options was
// used, then we need to derive the context, and content location, from
// the compiler.
if (!options.content || !options.content.length) {
options.content = [].concat(options.compiler.options.context || process.cwd());
}
const done = (stats) => {
const json = stats.toJson();
if (stats.hasErrors()) {
bus.emit('compiler-error', json);
}
if (stats.hasWarnings()) {
bus.emit('compiler-warning', json);
}
};
if (options.compiler.hooks) {
options.compiler.hooks.done.tap('WebpackServe', done);
} else {
options.compiler.plugin('done', done);
}
const { close, server, start } = getServer(options);
start(options);
for (const sig of ['SIGINT', 'SIGTERM']) {
process.on(sig, () => { // eslint-disable-line no-loop-func
close(() => {
log.info(`Process Ended via ${sig}`);
server.kill();
process.exit(0);
});
});
}
return Object.freeze({
close,
compiler: options.compiler,
on(...args) {
options.bus.on(...args);
},
options
});
})
.catch((err) => {
// eslint-disable-next-line no-console
console.log('An error was thrown while starting webpack-serve.\n ', err);
throw err;
});
};