dev-server.js 2.3 KB

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