记一次升级webpack包v4到v5

64 阅读2分钟

记一次升级包的经历, 比较特殊, 是涉及webpack的.

1. 首先是升级可以升级的包, 因为比较多, 考虑到一次性升级.

正常情况一般是一个个单独升级的, 但webpack比较特殊

yarn upgrade-interactive --latest

使用这个命令可以把所有的包升级到最新, 点击空格选中包升级

2. 然后开始看各种scripts有没有问题

1. 比如第一个webpack-dev-server -c webpack.config.js

发现跑不起来了, 查看文档说是contentBase已经被弃用了, 需要换成static的写法 github.com/webpack/web…

contentBase/contentBasePublicPath/serveIndex/watchContentBase/watchOptions/staticOptions options were moved to static option:

image.png

改掉之后就可以成功跑起来了.

2. 然后看yarn build

发现build出来的版本号有问题, 不会变, 发现是版本号不能用hash了, 要改成contenthash

When using [hash] placeholder in webpack configuration, consider changing it to [contenthash]. It is not the same, but proven to be more effective.

image.png

3. 可以去掉一些自定义的plugin

  • If you are using IgnorePlugin with a regular expression as argument, it takes an options object now: new IgnorePlugin({ resourceRegExp: /regExp/ }).

image.png

4. 可以删掉没有用的包, 比如这个cleanWebpackPlugin是用来删除打包的dist文件的, webpack5默认支持就可以不用这个包了

CleanWebpackPlugin does not clean in Webpack 5

From webpack v5, you can remove the clean-webpack-plugin plugin and use the output.clean option in your webpack config:

 output: {
    filename: 'utils.min.js',
    clean: true,
 }

otherwise it will throw a warning and say this plugin not work

clean-webpack-plugin: options.output.path not defined. Plugin disabled...

image.png

3. 检查打包的内容

完成上面这些之后, 发现可以打包完成, 那么要检查下打包出来的代码有没有问题

发现代码跑起来以后, 页面不可以访问, 看到console里面有一行错误

Uncaught ReferenceError: process is not

发现原因是因为webpack5默认去掉了node.js的polyfill, 所以需要手动用plugin再补充进来.

const webpack = require("webpack");

module.exports = { ... 
  plugins: [
   ...,
   new webpack.ProvidePlugin({
     process: "process/browser",
   })
  ]
}

最后再次打包, 重新检查, 页面没有问题了.