forked from transistorsoft/background-geolocation-console
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev.server.js
More file actions
87 lines (76 loc) · 2.3 KB
/
dev.server.js
File metadata and controls
87 lines (76 loc) · 2.3 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
77
78
79
80
81
82
83
84
85
86
87
/* eslint-disable no-console */
/* eslint-disable import/no-extraneous-dependencies */
import path from 'path';
import express from 'express';
import 'colors';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import httpProxy from 'http-proxy';
import {
port,
devPort,
} from './src/server/config';
import webpackConfig from './webpack.config';
const app = express();
const compiler = webpack(webpackConfig);
const make = apiAddress => {
const proxy = apiAddress
? httpProxy.createProxyServer({ target: apiAddress })
: httpProxy.createProxyServer();
proxy.on('error', (error, req, res) => {
if (error.code !== 'ECONNRESET') {
console.error('proxy error', error);
}
if (!res.headersSent) {
res.writeHead(500, { 'content-type': 'application/json' });
}
res.status(500).json({ error: 'proxy_error', reason: error.message });
});
return proxy;
};
const register = (a, proxy, p, apiAddress) => {
console.info(`Server ${a.name} will proxy ${p} to ${apiAddress}`);
a.use(p, (req, res) => {
proxy.web(req, res, { target: apiAddress });
});
};
const middleware = [
webpackDevMiddleware(compiler, {
port: devPort,
contentBase: path.join(__dirname, 'src', 'client'),
hot: true,
stats: { colors: true },
compress: true,
}),
webpackHotMiddleware(compiler, {
// eslint-disable-next-line no-console
log: console.log,
heartbeat: 2000,
path: '/__webpack_hmr',
}),
];
app.use(middleware);
[{ address: `http://localhost:${port}/api`, path: '/api' }].forEach(cfg => {
const proxy = make(cfg.address);
app.on('stop', () => proxy.close());
register(app, proxy, cfg.path, cfg.address);
});
app.get('*', (req, res, next) => {
const filename = path.join(compiler.outputPath, 'index.html');
compiler.outputFileSystem.readFile(filename, (err, result) => {
if (err) {
return next(err);
}
res.set('content-type', 'text/html');
res.send(result);
return res.end();
});
});
app.listen(devPort, () => {
console.log('Developer Server | port: %s'.green, devPort);
});
process.on('dev server Uncaught Exception', err => {
// eslint-disable-next-line no-console
console.error('<!> Exception %s: '.red, err.message, err.stack);
});