-
Notifications
You must be signed in to change notification settings - Fork 93
/
server.js
63 lines (53 loc) · 2 KB
/
server.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
import chokidar from 'chokidar';
import config from './webpack.config';
import cssModulesRequireHook from 'css-modules-require-hook';
import express from 'express';
import http from 'http';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
cssModulesRequireHook({generateScopedName: '[path][name]-[local]'});
const compiler = webpack(config);
const app = express();
// Serve hot-reloading bundle to client
app.use(webpackDevMiddleware(compiler, {
noInfo: true, publicPath: config.output.publicPath
}));
app.use(webpackHotMiddleware(compiler));
// Include server routes as a middleware
app.use(function(req, res, next) {
require('./server/app')(req, res, next);
});
// Do "hot-reloading" of express stuff on the server
// Throw away cached modules and re-require next time
// Ensure there's no important state in there!
const watcher = chokidar.watch('./server');
watcher.on('ready', function() {
watcher.on('all', function() {
console.log("Clearing /server/ module cache from server");
Object.keys(require.cache).forEach(function(id) {
if (/[\/\\]server[\/\\]/.test(id)) delete require.cache[id];
});
});
});
// Anything else gets passed to the client app's server rendering
app.get('*', function(req, res, next) {
require('./client/server-render')(req.path, function(err, page) {
if (err) return next(err);
res.send(page);
});
});
// Do "hot-reloading" of react stuff on the server
// Throw away the cached client modules and let them be re-required next time
compiler.plugin('done', function() {
console.log("Clearing /client/ module cache from server");
Object.keys(require.cache).forEach(function(id) {
if (/[\/\\]client[\/\\]/.test(id)) delete require.cache[id];
});
});
const server = http.createServer(app);
server.listen(3000, 'localhost', function(err) {
if (err) throw err;
const addr = server.address();
console.log('Listening at http://%s:%d', addr.address, addr.port);
});