-
Notifications
You must be signed in to change notification settings - Fork 184
/
start.js
295 lines (249 loc) · 9.41 KB
/
start.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import http from "http"
import https from "https"
import path from "path"
import express from "express"
import compression from "compression"
import bodyParser from "body-parser"
import WebpackDevMiddleware from "webpack-dev-middleware"
import WebpackHotMiddleware from "webpack-hot-middleware"
import handleCompilationErrors from "../handleCompilationErrors";
import reactServer from "../react-server";
import setupLogging from "../setupLogging";
import logProductionWarnings from "../logProductionWarnings";
import expressState from 'express-state';
import cookieParser from 'cookie-parser';
import chokidar from 'chokidar';
import buildWebpackConfigs from "../buildWebpackConfigs";
import buildWebpackCompilers from "../buildWebpackCompilers";
import reactServerCliRun from "../run";
const logger = reactServer.logging.getLogger(__LOGGER__);
let CHUNK_HASHES = {};
// if used to start a server, returns an object with two properties, started and
// stop. started is a promise that resolves when all necessary servers have been
// started. stop is a method to stop all servers. It takes no arguments and
// returns a promise that resolves when the server has stopped.
export default function start(options){
setupLogging(options);
logProductionWarnings(options);
const {
port,
bindIp,
hot,
compileOnStartup,
} = options;
const webpackInfo = buildWebpack(options);
const allStartingPromises = [];
if (hot || compileOnStartup) {
allStartingPromises.push(webpackInfo.client.compiledPromise);
allStartingPromises.push(webpackInfo.server.compiledPromise);
}
logger.notice("Starting server...");
const htmlServerPromise = startHtmlServer(options, webpackInfo);
allStartingPromises.push(htmlServerPromise.started);
if (hot) {
const configWatcher = watchConfigurationFiles(htmlServerPromise, options);
}
return {
stop: () => Promise.all([htmlServerPromise.stop()]),
started: Promise.all(allStartingPromises)
.catch(e => {
logger.error(e);
throw e
})
.then(() => logger.notice(`Ready for requests on ${bindIp}:${port}.`)),
};
}
// given the server routes file and a port, start a react-server HTML server at
// http://host:port/. returns an object with two properties, started and stop;
// see the default function doc for explanation.
const startHtmlServer = (options, webpackInfo) => {
const {
port,
bindIp,
httpsOptions,
customMiddlewarePath,
hot,
longTermCaching,
compileOnStartup,
} = options;
let webpackDevMiddlewareInstance;
const server = express();
if (hot) {
// We don't need to add the server compiler to anything because the clientCompiler runs the serverCompiler
webpackDevMiddlewareInstance = WebpackDevMiddleware(webpackInfo.client.compiler, {
//noInfo: (options.logLevel !== "debug"),
noInfo: true,
lazy: false,
publicPath: webpackInfo.client.config.output.publicPath,
log: logger.debug,
warn: logger.warn,
error: logger.error,
});
server.use(webpackDevMiddlewareInstance);
server.use(WebpackHotMiddleware(webpackInfo.client.compiler, {
log: logger.info,
path: '/__react_server_hmr__',
}));
} else {
if (compileOnStartup) {
// Only compile the webpack configs manually if we're not in hot mode and compileOnStartup is true
logger.notice("Compiling Webpack bundle prior to starting server...");
webpackInfo.client.compiler.run((err, stats) => {
const error = handleCompilationErrors(err, stats);
});
}
server.use('/', compression(), express.static(`__clientTemp/build`, {
maxage: longTermCaching ? '365d' : '0s',
}));
}
let middlewareSetup = (server, rsMiddleware) => {
server.use(compression());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
expressState.extend(server);
// parse cookies into req.cookies property
server.use(cookieParser());
// sets the namespace that data will be exposed into client-side
// TODO: express-state doesn't do much for us until we're using a templating library
server.set('state namespace', '__reactServerState');
rsMiddleware();
};
const webServer = httpsOptions ? https.createServer(httpsOptions, server) : http.createServer(server);
return {
stop: serverToStopPromise(webServer, webpackDevMiddlewareInstance),
started: new Promise((resolve, reject) => {
webpackInfo.server.routesFile.then(() => {
logger.info("Starting react-server...");
// Currently this refers to the first route in the webpack server config. This will need to be changed
// when server-side chunking is enabled.
const serverEntryPoint = path.join(webpackInfo.paths.serverOutputDirAbsolute,
Object.keys(webpackInfo.paths.serverEntryPoints)[0] + ".bundle.js");
let rsMiddlewareCalled = false;
const rsMiddleware = () => {
rsMiddlewareCalled = true;
server.use((req, res, next) => {
reactServer.middleware(req, res, next, require(serverEntryPoint));
});
};
if (customMiddlewarePath) {
const customMiddlewareDirAb = path.resolve(process.cwd(), customMiddlewarePath);
middlewareSetup = require(customMiddlewareDirAb).default;
}
middlewareSetup(server, rsMiddleware);
if (!rsMiddlewareCalled) {
logger.error("Error react-server middleware was never setup in custom middleware function");
reject("Custom middleware did not setup react-server middleware");
return;
}
webServer.on('error', (e) => {
logger.error("Error starting up react-server");
logger.error(e);
reject(e);
});
webServer.listen(port, bindIp, (e) => {
if (e) {
reject(e);
return;
}
logger.info(`Started react-server over ${httpsOptions ? "HTTPS" : "HTTP"} on ${bindIp}:${port}`);
resolve();
});
});
}),
};
};
// returns a method that can be used to stop the server. the returned method
// returns a promise to indicate when the server is actually stopped.
const serverToStopPromise = (server, webpackDevMiddlewareInstance) => {
const sockets = [];
// If we're hot reloading then we want to be able to bail out quickly. Zombie
// (the test browser) makes keepalive connections to our static asset
// server, and we don't need to be polite to it when we're tearing down.
// The Client-side HMR is also a ServerSentEvent with a long-running socket connection
if (process.env.NODE_ENV !== "production") { // eslint-disable-line no-process-env
server.on('connection', socket => sockets.push(socket));
}
return () => {
return new Promise((resolve, reject) => {
// This will only have anything if we're testing. See above.
sockets.forEach(socket => socket.destroy());
if (webpackDevMiddlewareInstance) {
webpackDevMiddlewareInstance.close();
}
server.on('error', (e) => {
logger.error('An error was emitted while shutting down the server');
logger.error(e);
reject(e);
});
server.close((e) => {
if (e) {
logger.error('The server was not started, so it cannot be stopped.');
logger.error(e);
reject(e);
return;
}
logger.notice('The server stopped.');
resolve();
});
});
};
};
function buildWebpack(options) {
let webpackInfo = buildWebpackConfigs(options);
if (options.hot || options.compileOnStartup) {
CHUNK_HASHES = {};
webpackInfo = buildWebpackCompilers(options, webpackInfo);
webpackInfo.client.compiledPromise = new Promise((resolve) => webpackInfo.client.compiler.plugin("done", () => resolve()));
webpackInfo.server.compiledPromise = new Promise((resolve) => webpackInfo.server.compiler.plugin("done", (stats) => {
if (options.hot && stats.compilation.errors.length === 0) {
// This is the meat of the server side "hot reloading" code. Essentially, we look iterate over the named
// chunks and, if their hashes are different from what we last saw, we delete the "require.cache" entry.
// The next time that file is "require()'d", NodeJS will read it from disk.
let chunk,
absoluteFilename;
for (let chunkName in stats.compilation.namedChunks) {
if (stats.compilation.namedChunks.hasOwnProperty(chunkName)) {
chunk = stats.compilation.namedChunks[chunkName];
if (typeof CHUNK_HASHES[chunkName] !== "undefined" && CHUNK_HASHES[chunkName] !== chunk.hash) {
for (let i in chunk.files) {
absoluteFilename = path.join(webpackInfo.paths.serverOutputDirAbsolute, chunk.files[i]);
logger.notice(`chunk ${chunkName} changed, hot reloading: ${absoluteFilename}`);
delete require.cache[absoluteFilename];
}
}
CHUNK_HASHES[chunkName] = chunk.hash;
}
}
}
resolve();
}));
}
return webpackInfo;
}
function watchConfigurationFiles(serverObj, options) {
const cwd = process.cwd();
const staticConfigFiles = [
path.resolve(cwd, ".reactserverrc"),
options.routesPath,
];
if (options.webpackConfig) {
staticConfigFiles.push(path.resolve(cwd, options.webpackConfig));
}
if (options.webpackClientConfig) {
staticConfigFiles.push(path.resolve(cwd, options.webpackClientConfig));
}
if (options.webpackServerConfig) {
staticConfigFiles.push(path.resolve(cwd, options.webpackServerConfig));
}
staticConfigFiles.forEach((path) => delete require.cache[path]);
logger.info("Watching react-server configuration files for changes: ", staticConfigFiles);
const watcher = chokidar.watch(staticConfigFiles);
watcher.on('change', (path) => {
logger.info(`File ${path} has been changed, restarting server`);
watcher.close();
serverObj.stop().then(() => {
reactServerCliRun({ command: "start" });
});
});
return watcher;
}