升级webpack5过程中遇到的坑

将项目的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"  
},

最后成功运行起来。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章