forked from easy-team/egg-webpack
/
server.js
88 lines (78 loc) · 2.75 KB
/
server.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
'use strict';
const Utils = require('./utils');
const msg_build_state = 'webpack_build_state';
const msg_build_success = 'webpack_build_success';
const msg_read_file_memory = 'webpack_read_file_memory';
const msg_read_file_memory_content = 'webpack_read_file_memory_content';
const WebpackTool = require('webpack-tool-x');
const build = require('./build');
class WebpackServer extends WebpackTool {
constructor(agent, config) {
super(config);
this.agent = agent;
this.compileDoneCount = 0;
this.browser = config.browser;
this.appPort = this.config.appPort || process.env.PORT || 7001;
this.compilerCount = this.config.webpackConfigList.length;
this.startTime = Date.now();
}
start() {
build.dll(this.config, { baseDir: this.agent.baseDir }, () => {
const compilers = [];
this.config.webpackConfigList.forEach((webpackConfig, index) => {
const compiler = this.build(webpackConfig);
super.createWebpackServer(compiler, {
hot: webpackConfig.target !== 'node',
target: webpackConfig.target,
port: this.config.port + index,
publicPath: webpackConfig.output.publicPath,
middlewares: this.config.middlewares,
}, webpackConfig);
compilers.push(compiler);
});
this.listen(compilers);
});
}
checkBuildState() {
if (!this.buildState) {
this.buildState = this.compileDoneCount > 0 && this.compileDoneCount % this.compilerCount === 0;
if (this.buildState) {
this.endTime = Date.now();
console.log(`webpack build cost:${this.endTime - this.startTime}ms`);
if (/^https?/.test(this.browser)) {
this.openBrowser(this.appPort, this.browser);
} else if (this.browser === undefined || this.browser === true) {
this.openBrowser(this.appPort);
}
}
}
return this.buildState;
}
build(webpackConfig) {
this.setConfig({ isServerBuild: true });
return super.build(webpackConfig, () => {
this.compileDoneCount++;
const state = this.checkBuildState();
if (state) {
this.agent.messenger.sendToApp(msg_build_state, { state });
}
this.agent[msg_build_success] = true;
});
}
listen(compilers) {
this.agent.messenger.on(msg_build_state, () => {
const state = this.checkBuildState();
if (state) {
this.agent.messenger.sendToApp(msg_build_state, { state });
}
});
this.agent.messenger.on(msg_read_file_memory, data => {
const filePath = data.filePath;
const fileContent = Utils.readWebpackMemoryFile(compilers, filePath, data.fileName);
this.agent.messenger.sendToApp(msg_read_file_memory_content, {
fileContent, filePath
});
});
}
}
module.exports = WebpackServer;