webpack-dev-server 为你提供了一个简单的 web 服务器,并且能够实时重新加载(live reloading
npm install --save-dev webpack-dev-server
特别注意,以下的版本是不兼容的
- webpack.config.js
- 注意,这里添加了devServer字段,用于配置webpack-dev-server
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {
CleanWebpackPlugin} = require('clean-webpack-plugin')
module.exports = {
entry: {
app1111: './src/index.js',
print: './src/print.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'eval',
devServer: {
contentBase: './dist'
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Output Management'
})
]
};
- package.json
- 这里在scripts中添加了start字段,使用npm start运行即可
{
"name": "webpack-demo1",
"version": "1.0.0",
"description": "",
"private": "true",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^4.5.0",
"webpack": "^5.1.0",
"webpack-cli": "^4.0.0"
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"lodash": "^4.17.20"
}
}
注意,这里会报错:Error: Cannot find module ‘webpack-cli/bin/config-yargs’
- 百度查找原因这是因为webpack、webpack-cli、webpack-dev-server是需要版本匹配的
运行以下版本是可行的,webpack.config.js文件不变,安装新版本的webpack和webpack-cli和webpack-dev-server,package.json文件如下
- “webpack”: “^4.43.0”,
“webpack-cli”: “^3.3.12”,
“webpack-dev-server”: “^3.11.0”
- 安装命令行代码
npm i webpack@4.43.0 webpack-cli@3.3.12 webpack-dev-server@3.11.0 webpack-dev-server -D
{
"name": "webpack-demo1",
"version": "1.0.0",
"description": "",
"private": "true",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^4.5.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"lodash": "^4.17.20"
}
}
- npm start运行
修改print.js,点击保存
export default function printMe () {
console.log('print.js');
console.error('我是一个错误')
}
export default function printMe () {
console.log('print.js');
}
- 运行npm start,这样就实现了实时打包,相当于补丁更新