-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathapp.js
66 lines (63 loc) · 2.23 KB
/
app.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
'use strict';
const path = require('path');
const fs = require('fs');
const WebpackTool = require('webpack-tool');
const convert = require('koa-convert');
const proxy = require('./lib/proxy');
const Constant = require('./lib/constant');
module.exports = app => {
app.use(async (ctx, next) => {
if (app.WEBPACK_BUILD_READY) {
await next();
} else {
if (app.WEBPACK_LOADING_TEXT) {
ctx.body = app.WEBPACK_LOADING_TEXT;
} else {
const filePath = path.resolve(__dirname, './lib/template/loading.html');
ctx.body = app.WEBPACK_LOADING_TEXT = fs.readFileSync(filePath, 'utf8');
}
}
});
app.messenger.setMaxListeners(app.config.webpack.maxListeners || 10000);
app.messenger.on(Constant.EVENT_WEBPACK_BUILD_STATE, data => {
app.WEBPACK_BUILD_READY = data.state;
const config = app.config.webpack;
const port = data.port || config.port;
if (!app.WEBPACK_BUILD_PROXY && config.proxy) {
app.WEBPACK_BUILD_PROXY = true;
if (typeof config.proxy === 'boolean') {
config.proxy = {
host: `http://127.0.0.1:${port}`,
match: /^\/public\//,
};
} else if (config.proxy.force !== true) {
config.proxy.host = `http://127.0.0.1:${port}`;
}
// 解决 proxy middleware 插入需要在静态资源和自定义中间件前面
let proxyIndex = -1;
const mwNames = ['static', 'bodyParser', 'overrideMethod', 'session', 'securities', 'notfound', 'siteFile', 'meta'];
while (mwNames.length) {
const name = mwNames.shift();
proxyIndex = app.middleware.findIndex(mw => {
return mw._name === name;
});
if (proxyIndex > -1) {
break;
}
}
app.middleware.splice(proxyIndex, 0, convert(proxy(config.proxy)));
}
});
app.messenger.on(Constant.EVENT_WEBPACK_OPEN_BROWSER, () => {
const appPort = app.options.port;
const browser = app.config.webpack.browser;
if (/^https?/.test(browser)) {
WebpackTool.utils.openBrowser(appPort, browser);
} else if (browser === undefined || browser === true) {
WebpackTool.utils.openBrowser(appPort);
}
});
app.ready(() => {
app.messenger.sendToAgent(Constant.EVENT_WEBPACK_BUILD_STATE);
});
};