terser-webpack-plugin 版本问题

链接
报错内容
在webpack 中使用压缩插件 terser-webpack-plugin
TypeError: Cannot read property 'javascript' of undefined.

报错详情

  1. D:\a>npm run build:qa
  2. > a@1.0.0 build:qa D:\a
  3. > cross-env webpack --env.ENVIRONMENT=qa --config ./webpack.config.js --mode production --progress --colors
  4. D:\a\node_modules\terser-webpack-plugin\dist\index.js:400
  5. const hooks = compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);
  6. ^
  7. TypeError: Cannot read property 'javascript' of undefined
  8. at D:\a\node_modules\terser-webpack-plugin\dist\index.js:400:38

解决方案
在webpack4 中使用了5版本的插件,更改版本

  1. terser-webpack-plugin": "^4.2.3"


terser-webpack-plugin 配置项

链接

需要将 mode 设置为 production 配置项中的设置才会生效
上面移除代码的一些配置应该是 UglifyJsPlugin 中的配置项,但是由于都是一个分支,所以是通用的。
在官方文档上并未看到这个配置的用法。

  1. const TerserPlugin = require("terser-webpack-plugin");
  2. module.exports = {
  3. mode: "production",
  4. entry: "./src/index.js",
  5. optimization: {
  6. minimize: true,
  7. minimizer: [
  8. new TerserPlugin({
  9. //使用 cache 加快二次构建速度
  10. cache: true,
  11. terserOptions: {
  12. comments: false,
  13. compress: {
  14. //删除无用代码
  15. unused: true,
  16. //删除debugger
  17. drop_debugger: true,
  18. //移除console
  19. drop_console: true,
  20. //移除无用代码
  21. dead_code: true,
  22. },
  23. },
  24. }),
  25. ],
  26. },
  27. };