从webpack3.x迁移webpack4遇到的问题

474 阅读1分钟

1:CommonsChunkPlugin被移除, 官方推荐用splitChunks

optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendor",
          chunks: "all"
        }
      }
    }
  }

此处有问题就是设置name为vendor之后,发现打包之后的文件并没有vendor.js,后来经过调试发现,是因为chunkFilename设置成了 [chunkhash].js导致输出文件名被覆盖了,

  output: {
    path: path.resolve(process.env.BUILD_DEST || "build"),
    publicPath: "/build",
    filename: "[name].js",
    chunkFilename: "[chunkhash].js"
  }

2:extract-text-webpack-plugin 替换成 mini-css-extract-plugin,如果需要吧css文件合并在splitChunks里面设置style。

      {
        test: /\.scss/,
        use: [MiniCssExtractPlugin.loader, "happypack/loader?id=scss"]
      }
      
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendor",
          chunks: "all"
        },
        //css代码合并
        styles: {
          name: "index",
          test: /.stylus|css$/,
          chunks: "all",
          enforce: true
        }
      }

      
      
 

3:HappyPack从3.0升级到5.0 ,cache属性已经废弃了。

{
     // cache: true,
      debug: true,
      id: "js",
      loaders: [
        {
          path: "babel-loader",
          query: {
            cacheDirectory: true
          }
        }
      ],
      threadPool: happyThreadPool
}

4:UglifyJsPlugin已经不需要配置,官方推荐设置mode属性,mode为production,会默认打开UglifyJsPlugin,详细配置参考官方文档https://www.webpackjs.com/concepts/mode/


// webpack.production.config.js
module.exports = {
+  mode: 'production',
-  plugins: [
-    new UglifyJsPlugin(/* ... */),
-    new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }),
-    new webpack.optimize.ModuleConcatenationPlugin(),
-    new webpack.NoEmitOnErrorsPlugin()
-  ]
}