webpack-dev-server创建一个服务器(http:
//localhost:8080),服务器监听指定目录下的文件,自动打包文件,默认将输出文件bundle
.js存于服务器的根目录中,并具有实时更新加载页面的功能,使用步骤如下:
1、安装webpack@4.43.0 webpack-cli@3.3.12 webpack-dev-server@3.11.0( webpack-dev-server的使用需要配合版本兼容的webpack和webpack-cli) :
npm i webpack@4.43.0 webpack-cli@3.3.12 webpack-dev-server@3.11.0 webpack-dev-server -D
2、修改webpack.config.js文件
在webpack.config.js文件中添加devServer节点
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
index: './src/index.js',
print: './src/print.js',
},
devtool: 'inline-source-map',
**//配置devServer
devServer: {
//指定服务器自动打包哪个文件夹下的文件
contentBase: './dist',
//默认publicPath:'/',输出文件,即bundle.js文件存于服务器的根目录中,此处也可更改存储路径
publicPath:'/'
},**
plugins: [
new HtmlWebpackPlugin({
title: 'Development',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
};
3、在src目录的.html文件中引入输出文件bundle.js
<script src="http://localhost:8080/bundle.js"></script>
4、修改package.json文件
在package.json文件的scripts节点中添加
"start"节点
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
//添加start节点
"start": "webpack serve --open",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "^4.5.0",
"webpack": "^5.4.0",
"webpack-cli": "^4.2.0",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"lodash": "^4.17.20"
}
}
5、执行命令npm start
之后即可修改src目录中的功能js文件,自动打包文件并实时更新加载页面