dev-server.js 2.3 KB

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