dev-server.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. require('./check-versions')(); // 检查 Node 和 npm 版本
  2. var config = require('../config');
  3. if(!process.env.NODE_ENV) {
  4. process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
  5. }
  6. var opn = require('opn')
  7. var path = require('path');
  8. var express = require('express');
  9. var webpack = require('webpack');
  10. var proxyMiddleware = require('http-proxy-middleware');
  11. var webpackConfig = require('./webpack.dev.conf');
  12. // default port where dev server listens for incoming traffic
  13. var port = process.env.PORT || config.dev.port;
  14. // automatically open browser, if not set will be false
  15. var autoOpenBrowser = !!config.dev.autoOpenBrowser;
  16. // Define HTTP proxies to your custom API backend
  17. // https://github.com/chimurai/http-proxy-middleware
  18. var proxyTable = config.dev.proxyTable;
  19. var app = express();
  20. var compiler = webpack(webpackConfig);
  21. var devMiddleware = require('webpack-dev-middleware')(compiler, {
  22. publicPath: webpackConfig.output.publicPath,
  23. quiet: true
  24. });
  25. var hotMiddleware = require('webpack-hot-middleware')(compiler, {
  26. log: () => {}
  27. });
  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. hotMiddleware.publish({
  32. action: 'reload'
  33. });
  34. cb()
  35. })
  36. });
  37. // compiler.apply(new DashboardPlugin());
  38. // proxy api requests
  39. Object.keys(proxyTable).forEach(function(context) {
  40. var options = proxyTable[context]
  41. if(typeof options === 'string') {
  42. options = {
  43. target: options
  44. }
  45. }
  46. app.use(proxyMiddleware(options.filter || context, options))
  47. });
  48. // handle fallback for HTML5 history API
  49. app.use(require('connect-history-api-fallback')());
  50. // serve webpack bundle output
  51. app.use(devMiddleware);
  52. // enable hot-reload and state-preserving
  53. // compilation error display
  54. app.use(hotMiddleware);
  55. // serve pure static assets
  56. var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory);
  57. app.use(staticPath, express.static('./static'));
  58. var uri = 'http://localhost:' + port
  59. devMiddleware.waitUntilValid(function() {
  60. console.log('> Listening at ' + uri + '\n')
  61. });
  62. module.exports = app.listen(port, function(err) {
  63. if(err) {
  64. console.log(err);
  65. return
  66. }
  67. // when env is testing, don't need open it
  68. if(autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
  69. opn(uri)
  70. }
  71. });