-
Notifications
You must be signed in to change notification settings - Fork 334
/
devServer.js
56 lines (49 loc) · 1.62 KB
/
devServer.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
import fs from 'fs'
import path from 'path'
import express from 'express'
import webpack from 'webpack'
/**
* Start an express server which uses webpack-dev-middleware to build and serve
* assets using Webpack's watch mode, and webpack-hot-middleware to hot reload
* changes in the browser.
*
* If static path config is also provided, express will also be used to serve
* static content from the given path.
*/
export default function server(webpackConfig, {fallback, noInfo, port, staticPath}) {
let app = express()
let compiler = webpack(webpackConfig)
app.use(require('webpack-dev-middleware')(compiler, {
noInfo,
publicPath: webpackConfig.output.publicPath,
stats: {
colors: true
}
}))
app.use(require('webpack-hot-middleware')(compiler))
if (staticPath) {
app.use(express.static(staticPath))
}
if (fallback) {
app.use((req, res, next) => {
// Only fall back for GET methods which accept HTML and don't appear to
// end with a file extension.
if (req.method !== 'GET' || !req.accepts('html') || /\.[\w]{1,4}$/i.test(req.path)) {
return next()
}
fs.readFile(path.resolve('public/index.html'), 'utf8', (err, html) => {
if (err) return next(err)
// Rewrite relative build URLs to be absolute so they work from any path
res.send(html.replace(/="build\//g, '="/build/'))
})
})
}
app.listen(port, 'localhost', err => {
if (err) {
console.error('nwb: error starting dev server:')
console.error(err.stack)
process.exit(1)
}
console.log(`nwb: dev server listening at http://localhost:${port}`)
})
}