记录一次webpack3.0升级到webpack4.x(4.46.0)的过程

363 阅读1分钟

【前言】

最近在升级chrome到99后发现source-map无法使用,怀疑是webpack(3.12.0)版本太旧导致新版chrome不支持了(虽然最后通过其他方式解决了),所以对webpack版本进行了一次升级。看了下webpack4.x的最后一个版本是4.46.0,webpack5.x还在迭代中。作为一个老项目,稳定压倒一切,除非逼不得已, 所以选择了4.46作为这次版本升级的目标。

【过程】

先对webpack四大基石进行下排查(entry, output, loader, plugins), 剩下都是修修补补了。

  1. loader中的extract-text-webpack-plugin已经不适配了,用mini-css-extract-plugin替代
  2. 给每个loader中加入cache-loader进行缓存处理
  3. hard-source-webpack-plugin代替原先的dllplugin方案
  4. progress-bar-webpack-plugin增加打包进度条,增加体验
  5. 增加optimization, 配合上面的插件进行打包,压缩,souce-map处理, 代码如下:
  ...other option
  mode: 'development',
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendors: {
          name: 'vendor',
          test: /[\\\/]node_modules[\\\/]/,
          priority: -10,
          chunks: 'initial'
        },
        common: {
          name: 'chunk-common',
          minChunks: 2,
          priority: -20,
          chunks: 'initial',
          reuseExistingChunk: true
        }
      }
    },
    minimizer: [
      /* config.optimization.minimizer('terser') */
      new TerserPlugin({
        terserOptions: {
          compress: {
            arrows: false,
            collapse_vars: false,
            comparisons: false,
            computed_props: false,
            hoist_funs: false,
            hoist_props: false,
            hoist_vars: false,
            inline: false,
            loops: false,
            negate_iife: false,
            properties: false,
            reduce_funcs: false,
            reduce_vars: false,
            switches: false,
            toplevel: false,
            typeofs: false,
            booleans: true,
            if_return: true,
            sequences: true,
            unused: true,
            conditionals: true,
            dead_code: true,
            evaluate: true
          },
          mangle: {
            safari10: true
          }
        },
        sourceMap: true,
        cache: true,
        parallel: true,
        extractComments: false
      })
    ]
  },