/
dev.js
113 lines (106 loc) · 3.05 KB
/
dev.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import {
createCompiler,
prepareUrls,
} from 'react-dev-utils/WebpackDevServerUtils';
import clearConsole from 'react-dev-utils/clearConsole';
import openBrowser from 'react-dev-utils/openBrowser';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import chalk from 'chalk';
import errorOverlayMiddleware from './errorOverlayMiddleware';
import send, { STARTING, COMPILING, DONE } from './send';
import choosePort from './choosePort';
const isInteractive = process.stdout.isTTY;
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 8000;
const HOST = '0.0.0.0';
const PROTOCOL = 'http';
const noop = () => {};
process.env.NODE_ENV = 'development';
export default function dev({
webpackConfig,
extraMiddlewares,
beforeServer,
afterServer,
onCompileDone = noop,
onCompileInvalid = noop,
proxy,
openBrowser: openBrowserOpts,
}) {
if (!webpackConfig) {
throw new Error('必须提供 webpackConfig 配置项');
}
choosePort(DEFAULT_PORT)
.then(port => {
if (port === null) {
return;
}
const urls = prepareUrls(PROTOCOL, HOST, port);
const compiler = createCompiler(webpack, webpackConfig, 'Your App', urls);
// Webpack startup recompilation fix. Remove when @sokra fixes the bug.
// https://github.com/webpack/webpack/issues/2983
// https://github.com/webpack/watchpack/issues/25
const timefix = 11000;
compiler.plugin('watch-run', (watching, callback) => {
watching.startTime += timefix;
callback();
});
compiler.plugin('done', stats => {
send({ type: DONE });
stats.startTime -= timefix;
onCompileDone();
});
compiler.plugin('invalid', () => {
send({ type: COMPILING });
onCompileInvalid();
});
const serverConfig = {
disableHostCheck: true,
compress: true,
clientLogLevel: 'none',
hot: true,
quiet: true,
publicPath: webpackConfig.output.publicPath,
watchOptions: {
ignored: /node_modules/,
},
historyApiFallback: {
disableDotRule: true,
},
overlay: false,
host: HOST,
proxy,
before(app) {
if (extraMiddlewares) {
extraMiddlewares.forEach(middleware => {
app.use(middleware);
});
}
app.use(errorOverlayMiddleware());
},
};
const devServer = new WebpackDevServer(compiler, serverConfig);
if (beforeServer) {
beforeServer(devServer);
}
devServer.listen(port, HOST, err => {
if (err) {
console.log(err);
return;
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
if (openBrowserOpts) {
openBrowser(urls.localUrlForBrowser);
}
send({ type: STARTING });
if (afterServer) {
afterServer(devServer);
}
});
})
.catch(err => {
console.log(err);
});
}