以后简书不写技术了。
搬过来
会根据每天的内容持续更新
针对dev和prod要不同的配置
代码压缩: 官方建议使用UglifyJsPlugin
plugins: [
new webpack.optimize.UglifyJsPlugin({
sourceMap: true
})
]
webpack官方给了三种本地开发方式
watch方式太简单了不说了
webpack-dev-middleware为一个内建express服务器
webpack-hot-middleware为一中间层插件,用于热加载更新网页,需基于webpack-dev-middleware
http-proxy-middle作为中间proxy层转发
webpack-dev-middleware不会将文件打包到真是硬盘上,而是打包到内存中,通过webpack.config.js获取到webpack文件,随后将其打包到内存中
var webpack = require('webpack')
var webpackConfig = require('./webpack.config')
var compiler = webpack(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
// quiet: true, // quite mode won't output compile message in console
})
服务器则采用express实现
var express = require('express')
var app = express();
app.use(devMiddleware);
文件结构发生变化时会触发重编译(watch-mode下)
compiler.plugin('compilation', function (compilation) {
console.log('compilation');
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
// do sth here, mostly hot-middleware
cb();
});
})
原理
// TODO
参考
在webpack-dev-middleware中无法使用chunkhash,需要在webpack.config.js中针对不同对环境配置
hotmiddleware基于devmiddleware
在server配置文件中需要加上
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: false,
heartbeat: 2000
})
app.use(hotMiddleware)
同时,在重新编译后要通过hotmiddleware推送
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
console.log('compilation')
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
最后,在webpack.config.dev.js
中需要加上两条
entry中的app加入client
require('eventsource-polyfill'); // 这条的作用是兼容ie没有event
var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true');
hotClient.subscribe(function (event) {
// client端,通过event事件触发,类型为reload时触发页面刷新
if (event.action === 'reload') {
window.location.reload();
}
});
plugins加上
plugins: [
// OccurenceOrderPlugin is needed for webpack 1.x only
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
// Use NoErrorsPlugin for webpack 1.x
new webpack.NoEmitOnErrorsPlugin()
]
作为代理转发层
在server配置文件中加上
app.use(require('http-proxy-middleware')(
filter,
{
target,
}
));
其中filter对应需要代理的请求,target是代理转发的域名
例如
app.use(require('http-proxy-middleware')(
'/login',
{
target: 'http://localhost:3000'
}
));
会将所有的”/login”请求转发到localhost:3000下