将项目的weback从3升到了5,遇到了一系列的问题,这里分享两个问题的解决方案。
1.extract-text-webpack-plugin兼容问题
2.webpack-dev-server兼容问题
1.extract-text-webpack-plugin兼容问题
升到webpack5后,运行打包直接报错,如下:
分析原因
webpack4以上的版本不再使用“extract-text-webpack-plugin”,应该改成用“mini-css-extract-plugin”
解决方案
原代码:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
plugins: [
new ExtractTextPlugin({ filename:'[name].css', disable: false, allChunks: true })
],
module: {
loaders: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback:'style-loader',
use:'css-loader!less-loader' })
}
]
}
}
改为:
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css"
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader"
]
}
]
}
}
2.webpack-dev-server兼容问题
在npm run dev 启动服务的时候报错
分析原因
目前webpack-dev-server版本不支持webpack5.0和webpack-cli4.0
解决方案:修改package.json中的配置
原代码:
"scripts": {
"dev": "webpack-dev-server --config webpack.config.dev.js",
"build": "webpack --config webpack.config.prod.js"
},
改为:
"scripts": {
"dev": "webpack serve --mode development --env development --config webpack.config.dev.js",
"build": "webpack --config webpack.config.prod.js"
},
最后成功运行起来。