Repository navigation
Expand file tree
/
Copy pathdev-static.js
More file actions
76 lines (62 loc) · 1.84 KB
/
Copy pathdev-static.js
File metadata and controls
76 lines (62 loc) · 1.84 KB
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
const axios = require('axios')
const path = require('path')
const webpack = require('webpack')
const MemoryFs = require('memory-fs')
const proxy = require('http-proxy-middleware')
const serverRender = require('./server-render')
const serverConfig = require('../../build/webpack.config.server')
const getTemplate = () => {
return new Promise((resolve, reject) => {
axios.get('http://localhost:8888/public/server.ejs')
.then(res => {
resolve(res.data)
})
.catch(reject)
})
}
const NativeModule = require('module')
const vm = require('vm')
const getModuleFromString = (bundle, filename) => {
const m = {exports: {}}
const wrapper = NativeModule.wrap(bundle)
const script = new vm.Script(wrapper, {
filename: filename,
displayErrors: true,
})
const result = script.runInThisContext()
result.call(m.exports, m.exports, require, m)
return m
}
const mfs = new MemoryFs();
serverConfig.mode = 'development'
const serverCompiler = webpack(serverConfig);
serverCompiler.outputFileSystem = mfs;
let serverBundle
serverCompiler.watch({}, (err, stats) => {
if (err) {
throw err;
}
stats = stats.toJson();
stats.errors.forEach(err => console.error(err))
stats.warnings.forEach(warn => console.warn(warn))
const bundlePath = path.join(
serverConfig.output.path,
serverConfig.output.filename
)
const bundle = mfs.readFileSync(bundlePath, 'utf-8');
const m = getModuleFromString(bundle, 'server-entry.js')
serverBundle = m.exports
})
module.exports = function (app) {
app.use('/public', proxy({
target: 'http://localhost:8888'
}));
app.get('*', function (req, res, next) {
if(!serverBundle) {
return res.send('waiting for compile, refresh later')
}
getTemplate().then(template => {
return serverRender(serverBundle, template, req, res)
}).catch(next)
})
}