dev-server.js 2.1 KB

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