dev-server.js 2.1 KB

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