webpack5之devServer
Posted 开发手记
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了webpack5之devServer相关的知识,希望对你有一定的参考价值。
现在我们每次更改src目录下文件的时候,都需要手动运行一下打包命令,这是非常不利于开发体验的,因此,我们需要改良一下,引入webpack-dev-server。
npm i webpack-dev-server -D
webpack.config.js的配置如下:(webpack5必须要配置target)
const { resolve } = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');//打包html
const miniCssExtractPlugin = require('mini-css-extract-plugin');//分离样式
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');//压缩css
module.exports = {
entry: './src/main.js',
output: {
filename: 'bundle.js',
path: resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: [miniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
},
{
test: /\.less$/,
use: [miniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'less-loader']
},
{
test: /\.scss$/,
use: [miniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader']
},
{
test: /\.(jpg|jpeg|png|gif)$/,
loader: "url-loader",
options: {
limit: 1024 * 10,
outputPath: 'imgs',
publicPath: './imgs',
esModule: false
}
},
{
test: /\.(htm|html)$/,
loader: 'html-loader',
options: {
esModule: false
}
},
{
test: /\.(eot|woff|ttf|svg)$/,
loader: 'file-loader',
options: {
outputPath: 'fonts',
publicPath: './fonts'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/assets/index.html',
hash: true,
filename: 'index.html',
favicon: './src/assets/favicon.ico'
}),
new miniCssExtractPlugin({
filename: 'index.css'
}),
new OptimizeCssAssetsWebpackPlugin()
],
mode: 'development',
devServer: {
contentBase: resolve(__dirname, 'dist'),//打包后的文件路径
open: true,//自动打开浏览器
compress: true,//启动gzip压缩
port: 3000,//端口号
},
target: 'web',
}
package.json的配置如下:(运行一下npm run serve就OK啦)
{
"name": "wpk5-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"serve": "npx webpack serve",
"build": "npx webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^5.2.0",
"file-loader": "^6.2.0",
"html-loader": "^2.1.2",
"html-webpack-plugin": "^5.3.1",
"less": "^4.1.1",
"less-loader": "^8.0.0",
"mini-css-extract-plugin": "^1.4.0",
"node-sass": "^5.0.0",
"optimize-css-assets-webpack-plugin": "^5.0.4",
"postcss-loader": "^5.2.0",
"postcss-preset-env": "^6.7.0",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0",
"url-loader": "^4.1.1",
"webpack": "^5.28.0",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
https://gitee.com/seimin/xiaoming2qianduan-webpack5/tree/v5.8/
以上是关于webpack5之devServer的主要内容,如果未能解决你的问题,请参考以下文章
微前端之 Webpack5 的 module federation
微前端之 Webpack5 的 module federation
webpack配置详解 - entry - output - module - resolve - dev server - optimization - webpack5