webpack-dev-server用于开发调试,它提供了web服务、热更新、接口代理等支持。
我们在上一篇的基础上添加webpack-dev-server功能
首先在项目中安装webpack-dev-server
npm i --save-dev webpack-dev-server
package.json
内容如下
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^1.0.0",
"file-loader": "^2.0.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.4.3",
"style-loader": "^0.23.0",
"url-loader": "^1.1.1",
"webpack": "^4.19.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.8"
}
}
在webpack.config.js
中添加devServer
选项,制定web服务器的文件目录和入口
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
index: './src/js/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].[hash:8].js'
},
module: {
...
},
plugins: [
...
],
devServer: {
contentBase: path.resolve(__dirname, "../dist/"),
index:'./page/index.html'
}
};
由于webpack-dev-server没有全局安装,所以在package.json
的“scripts”中添加webpack-dev-server
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"dev": "webpack-dev-server --inline --progress --compress --hot --open --config webpack.config.js --host 127.0.0.1 --port 8888"
},
最后,执行npm run dev
,webpack编译打包完成后,会自动打开浏览器访问devServer中指定的页面(因为使用了--open选项)。
webpack-dev-server更多用法及常用选项可以使用webpack-dev-server --help
命令查看。
网友评论