-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
81 lines (78 loc) · 2.42 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
// ts-check
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const webpack = require('webpack');
const webpackMiddleware = require('webpack-dev-middleware');
const RUNNING = process.argv.includes('start')
const getWebpackConfig = (config_file, conf) => {
const cfg_path = path.join(conf.root, config_file)
if (fs.existsSync(cfg_path)) {
const cfg = require(cfg_path)
if (typeof cfg === 'function') {
return [].concat(cfg(conf))
} else {
return [].concat(cfg)
}
} else {
throw Error(`${config_file} needed!`)
}
}
/**
* @returns {import('f2e-server').Middleware}
*/
module.exports = (conf, opt = {}) => {
const { build, root, gzip, output } = conf
const {
setBefore,
test = /^static\//,
config_file = 'webpack.config.js',
running = RUNNING,
options = {}
} = opt;
const get_compiler = () => {
const configs = getWebpackConfig(config_file, conf)
return webpack(configs.map(c => Object.assign({
context: root,
devtool: build ? false : 'source-map',
mode: build ? 'production' : 'development'
}, c, {
output: Object.assign({}, c.output, { path: output })
})))
}
let app;
if (!running) {
get_compiler().run(function (error, stat) {
if (error) {
console.log(error)
} else {
console.log(stat.toString())
}
})
}
return {
setBefore,
onRoute: running ? (pathname, req, resp) => {
if (test.test(pathname)) {
app = app || webpackMiddleware(get_compiler(), Object.assign({
}, options))
const _end = resp.end.bind(resp)
let end = _end
if (gzip) {
end = function (content, ...args) {
const result = zlib.gzipSync(content)
resp.setHeader('Content-Encoding', 'gzip')
resp.setHeader('Content-Length', result.length)
_end(result, ...args)
}
}
app(req, Object.assign(resp, {
end
}), function () {
resp.end('')
})
return false
}
} : undefined
}
}