如果简单的解决浏览器在修改文件后刷新,可以使用webpack --watch 启动监听文件,还有一种方式就是使用webpack-dev-server,它不仅仅支持简单的监听文件修改刷新界面,还支持 Hot Module Replacement (HMR),这个可以使你不再刷新整个页面,例如:在使用React时,你会体会到它的好处
安装webpack-dev-server
npm i webpack-dev-server --save-dev
如果你迫不及待想要使用这个体验一下,自动刷新的新功能,执行 webpack-dev-server --inline
将webpack-dev-server加入项目中
package.json
...
"start": "webpack-dev-server",
...
执行npm start 或者npm run start
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from /Users/krock/Documents/web/my-project
Hash: 22e371d51a6f1503edf9
Version: webpack 1.13.3
Time: 676ms
Asset Size Chunks Chunk Names
app.js 1.78 kB 0 [emitted] app
index.html 180 bytes [emitted]
chunk {0} app.js (app) 302 bytes [rendered]
[0] ./app/index.js 120 bytes {0} [built]
[1] ./app/component.js 182 bytes {0} [built]
Child html-webpack-plugin for "index.html":
chunk {0} index.html 540 kB [rendered]
[0] ./~/html-webpack-plugin/lib/loader.js!./~/html-webpack-plugin/default_index.ejs 540 bytes {0} [built]
[1] ./~/lodash/lodash.js 539 kB {0} [built]
[2] (webpack)/buildin/module.js 241 bytes {0} [built]
webpack: bundle is now VALID.
访问:http://localhost:8080/webpack-dev-server/ 就可以看到你的网站页面了,试试修改component.js中的内容,是否没有手动刷新就出现了呢?
如果没有出现界面内容,查看是否8080端口被占用,使用webpack-dev-server --port 3000 修改端口启动网站
配置HMR
如果想要立即体验效果可使用webpack-dev-server --inline --hot
新建libs/parts.js
此文件中包含webpack.config中要使用的各种配置
const webpack = require('webpack');
exports.devServer = function(options) {
return {
devServer: {
historyApiFallback: true,
hot: true,
inline: true,
stats: 'errors-only',
host: options.host, // 默认 to `localhost`
port: options.port // 默认 to 8080
},
plugins: [
//开启多通道编译,能获得更好的性能
new webpack.HotModuleReplacementPlugin({
multiStep: true
})
]
};
};
webpack.config.js
...
const parts = require('./libs/parts');
...
switch(process.env.npm_lifecycle_event) {
case 'build':
config = merge(common, {});
break;
default:
config = merge(
common,
parts.devServer({
host: process.env.HOST,
port: process.env.PORT
})
);
}
...
访问localhost:8080,修改文件看看效果
以上设置可能在某些版本windows\ubuntu等中有问题
解决此问题,需增加如下配置/libs/parts.js
const webpack = require('webpack');
exports.devServer = function(options) {
return {
watchOptions: {
// Delay the rebuild after the first change
aggregateTimeout: 300,
// Poll using interval (in ms, accepts boolean too)
poll: 1000
},
devServer: {
...
},
...
};
}
事实上你还可以使用express做服务器,使用webpack-dev-server为中间件(我没用过,暂时不多说)
下一章内容
css的自动更新和配置loader
进入下一章-css配置
本系列文章参考自surviceJS