1、观察模式
package.json中加入”watch“:
{
"name": "111",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch":"webpack --watch",
"build": "webpack"
},
在终端运行npm
使用观察模式,webpack可以自动重新编译修改后的模块,但是不能自动刷新浏览器,需要手动点击刷新
2、使用webpack-dev-server
添加devServer
module.exports = {
entry:{
app:'./src/index.js',
print:'./src/print.js'
},
devtool:'inline-source-map',
devServer:{
contentBase:'./dist'
},
output: {
filename:'[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
};
安装工具:
添加script运行脚本"start":
{
"name": "111",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch":"webpack --watch",
"start":"webpack-dev-server --open",
"build": "webpack"
},
在终端运行:npm start
在dev-server中,web服务器就会自动加载更新页面,我们可以随意修改和保存,服务器会自动帮我们重新加载,强烈推荐!
3、webpck-dev-middleware
安装插件:
设置配置:
output: {
filename:'[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath:'/'
},
添加server.js文件:
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);
// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}));
// Serve the files on port 3000.
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});
添加srcipt运行脚本”server“:
{
"name": "111",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"start": "webpack-dev-server --open",
"server":"node server.js",
"build": "webpack"
},
运行脚本:
此时打开浏览器跳转到localhost:3000,可以发现webpack程序已经运行!