UNPKG

1.68 kBJavaScriptView Raw
1const path = require('path')
2const express = require('express')
3const proxyMiddleware = require('http-proxy-middleware')
4
5module.exports = function (compiler, options = {}) {
6 const server = express()
7
8 const port = options.port
9 const host = options.host
10
11 const devMiddleWare = require('webpack-dev-middleware')(compiler, {
12 quiet: true,
13 publicPath: compiler.options.output.publicPath,
14 path: `http://${host}:${port}/__webpack_hmr`
15 })
16
17 server.use(devMiddleWare)
18 server.use(require('webpack-hot-middleware')(compiler, {
19 log: () => null
20 }))
21
22 if (options.setupDevServer) {
23 options.setupDevServer(server)
24 }
25
26 const mfs = devMiddleWare.fileSystem
27 const file = path.join(compiler.options.output.path, 'index.html')
28
29 // proxy api requests
30 if (typeof options.proxy === 'string') {
31 server.use(proxyMiddleware('/api', {
32 target: options.proxy,
33 changeOrigin: true,
34 pathRewrite: {
35 '^/api': ''
36 }
37 }))
38 } else if (typeof options.proxy === 'object') {
39 Object.keys(options.proxy).forEach(context => {
40 let proxyOptions = options.proxy[context]
41 if (typeof proxyOptions === 'string') {
42 proxyOptions = {
43 target: proxyOptions,
44 changeOrigin: true,
45 pathRewrite: {
46 [`^${context}`]: ''
47 }
48 }
49 }
50 server.use(proxyMiddleware(context, proxyOptions))
51 })
52 }
53
54 server.use(require('connect-history-api-fallback')({ index: '/' }))
55
56 server.get('/', (req, res) => {
57 devMiddleWare.waitUntilValid(() => {
58 const html = mfs.readFileSync(file)
59 res.end(html)
60 })
61 })
62
63 return { server, devMiddleWare, port, host }
64}