dev-server.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. // FIXME: This supposed to reload whole page when index.html is changed,
  31. // however now it reloads entire page on every breath, i suppose the order
  32. // of plugins changed or something. It's a minor thing and douesn't hurt
  33. // disabling it, constant reloads hurt much more
  34. // hotMiddleware.publish({ action: 'reload' })
  35. // cb()
  36. })
  37. })
  38. // proxy api requests
  39. Object.keys(proxyTable).forEach(function (context) {
  40. var options = proxyTable[context]
  41. if (typeof options === 'string') {
  42. options = { target: options }
  43. }
  44. app.use(proxyMiddleware(context, options))
  45. })
  46. // handle fallback for HTML5 history API
  47. app.use(require('connect-history-api-fallback')())
  48. // serve webpack bundle output
  49. app.use(devMiddleware)
  50. // enable hot-reload and state-preserving
  51. // compilation error display
  52. app.use(hotMiddleware)
  53. // serve pure static assets
  54. var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
  55. app.use(staticPath, express.static('./static'))
  56. module.exports = app.listen(port, function (err) {
  57. if (err) {
  58. console.log(err)
  59. return
  60. }
  61. var uri = 'http://localhost:' + port
  62. console.log('Listening at ' + uri + '\n')
  63. // opn(uri)
  64. })