dev-server.js 2.0 KB

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