-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-dev-utils.js
84 lines (70 loc) · 2.22 KB
/
server-dev-utils.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
function runServerCompiler(config) {
const path = require("path");
const fs = require("fs");
const child_process = require("child_process");
const proc = child_process.fork("./server-dev-server-compiler.js");
const task = new Promise(resolve => {
let context = { render: null };
proc.on("message", stats => {
const resolveContext = !context.render;
const { assetsByChunkName, entrypoints } = stats;
const main = Array.isArray(assetsByChunkName.main)
? assetsByChunkName.main[0]
: assetsByChunkName.main;
// important to normlize path otherwise delete require[fn] won't work cross platform
const fn = path.normalize(
path.resolve(__dirname, `build/server/${main}`)
);
// the main file name should be unique per build
try {
const serverRenderer = require(fn);
// console.log("[require(fn)]", serverRenderer); // todo: verbose
for (const func of ["render", "renderError"]) {
if (!(typeof serverRenderer[func] === "function")) {
console.warn(
`Warning: server-side bundle does not export expected function '${func}'`
);
continue;
}
context[func] = serverRenderer[func];
}
context.requireError = null;
} catch (requireError) {
console.error(`Error: cannot load file '${fn}'`);
console.error("----------------");
console.error(requireError);
console.error("----------------");
context.requireError = requireError;
return;
} finally {
if (context.fn) {
delete require.cache[context.fn];
fs.unlink(context.fn, err => err && console.warn(err));
const sourceMap = `${fs.context}.map`;
if (fs.existsSync(sourceMap)) {
fs.unlink(sourceMap, err => err && console.warn(err));
}
}
context.fn = fn;
}
if (resolveContext) {
resolve(context);
}
});
});
proc.send(
{
cmd: "start",
config
},
err =>
err && console.error("cannot spawn/start server compiler process", err)
);
return {
proc,
task
};
}
module.exports = {
runServerCompiler
};