|
| 1 | +require('./check-versions')() |
| 2 | +var config = require('../config') |
| 3 | +if (!process.env.NODE_ENV) process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) |
| 4 | +var path = require('path') |
| 5 | +var express = require('express') |
| 6 | +var webpack = require('webpack') |
| 7 | +var opn = require('opn') |
| 8 | +var proxyMiddleware = require('http-proxy-middleware') |
| 9 | +var webpackConfig = require('./webpack.dev.conf') |
| 10 | + |
| 11 | +// default port where dev server listens for incoming traffic |
| 12 | +var port = process.env.PORT || config.dev.port |
| 13 | +// Define HTTP proxies to your custom API backend |
| 14 | +// https://github.com/chimurai/http-proxy-middleware |
| 15 | +var proxyTable = config.dev.proxyTable |
| 16 | + |
| 17 | +var app = express() |
| 18 | +var compiler = webpack(webpackConfig) |
| 19 | + |
| 20 | +var devMiddleware = require('webpack-dev-middleware')(compiler, { |
| 21 | + publicPath: webpackConfig.output.publicPath, |
| 22 | + quiet: true |
| 23 | +}) |
| 24 | + |
| 25 | +var hotMiddleware = require('webpack-hot-middleware')(compiler, { |
| 26 | + log: () => {} |
| 27 | +}) |
| 28 | +// force page reload when html-webpack-plugin template changes |
| 29 | +compiler.plugin('compilation', function (compilation) { |
| 30 | + compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { |
| 31 | + hotMiddleware.publish({ action: 'reload' }) |
| 32 | + cb() |
| 33 | + }) |
| 34 | +}) |
| 35 | + |
| 36 | +// proxy api requests |
| 37 | +Object.keys(proxyTable).forEach(function (context) { |
| 38 | + var options = proxyTable[context] |
| 39 | + if (typeof options === 'string') { |
| 40 | + options = { target: options } |
| 41 | + } |
| 42 | + app.use(proxyMiddleware(context, options)) |
| 43 | +}) |
| 44 | + |
| 45 | +// handle fallback for HTML5 history API |
| 46 | +app.use(require('connect-history-api-fallback')()) |
| 47 | + |
| 48 | +// serve webpack bundle output |
| 49 | +app.use(devMiddleware) |
| 50 | + |
| 51 | +// enable hot-reload and state-preserving |
| 52 | +// compilation error display |
| 53 | +app.use(hotMiddleware) |
| 54 | + |
| 55 | +// serve pure static assets |
| 56 | +var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) |
| 57 | +app.use(staticPath, express.static('./static')) |
| 58 | + |
| 59 | +var uri = 'http://localhost:' + port |
| 60 | + |
| 61 | +devMiddleware.waitUntilValid(function () { |
| 62 | + console.log('> Listening at ' + uri + '\n') |
| 63 | +}) |
| 64 | + |
| 65 | +module.exports = app.listen(port, function (err) { |
| 66 | + if (err) { |
| 67 | + console.log(err) |
| 68 | + return |
| 69 | + } |
| 70 | + |
| 71 | + // when env is testing, don't need open it |
| 72 | + if (process.env.NODE_ENV !== 'testing') { |
| 73 | + opn(uri) |
| 74 | + } |
| 75 | +}) |
0 commit comments