dev-server.js 1.9 KB

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