开发脚本dev-server.js
The compiler object represents the fully configured Webpack environment. This object is built once upon starting Webpack, and is configured with all operational settings including options, loaders, and plugins.
A compilation object represents a single build of versioned assets
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 var config = require('../config')if (!process.env.NODE_ENV) process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) // "development"var path = require('path')var express = require('express')var webpack = require('webpack')var opn = require('opn')var proxyMiddleware = require('http-proxy-middleware')var webpackConfig = require('./webpack.dev.conf')// default port where dev server listens for incoming trafficvar port = process.env.PORT || config.dev.port// Define HTTP proxies to your custom API backend// https://github.com/chimurai/http-proxy-middlewarevar server = express()var compiler = webpack(webpackConfig)var devMiddleware = require('webpack-dev-middleware')(compiler, { // 将打包后文件放内存publicPath: webpackConfig.output.publicPath, //和webpack的output的一样stats: {colors: true,chunks: false}})var hotMiddleware = require('webpack-hot-middleware')(compiler) //热重载// force page reload when html-webpack-plugin template changes//While running Webpack development middleware, a new compilation will be created each time a file change is detected, thus generating a new set of compiled assets.compiler.plugin('compilation', function(compilation) { // webpack在compile时的回调//The Compiler has emitted all assets.compilation.plugin('html-webpack-plugin-after-emit', function(data, cb) { //文件由webpack生成后hotMiddleware.publish({action: 'reload'})cb()})})var context = config.dev.contextvar proxypath = config.dev.proxypathvar options = {target: proxypath,changeOrigin: true,}if (context.length) {server.use(proxyMiddleware(context, options))}server.use(proxyMiddleware('/payapi', {target: 'https://pay.ele.me',changeOrigin: true,}))server.use(proxyMiddleware('/m.ele.me@json', {target: 'https://crayfish.elemecdn.com',changeOrigin: true,}))// handle fallback for HTML5 history APIserver.use(require('connect-history-api-fallback')())serve webpack bundle outputserver.use(devMiddleware)enable hot-reload and state-preservingcompilation error displayserver.use(hotMiddleware)// serve pure static assetsvar staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)server.use(staticPath, express.static('./static'))module.exports = server.listen(port, function(err) {if (err) {console.log(err)return}var uri = 'http://localhost:' + portconsole.log('Listening at ' + uri + '\n')// when env is testing, don't need open itif (process.env.NODE_ENV !== 'testing') {opn(uri)}})