terser-webpack-plugin 版本问题
链接
报错内容
在webpack 中使用压缩插件 terser-webpack-plugin TypeError: Cannot read property 'javascript' of undefined
.
报错详情
D:\a>npm run build:qa
> a@1.0.0 build:qa D:\a
> cross-env webpack --env.ENVIRONMENT=qa --config ./webpack.config.js --mode production --progress --colors
D:\a\node_modules\terser-webpack-plugin\dist\index.js:400
const hooks = compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);
^
TypeError: Cannot read property 'javascript' of undefined
at D:\a\node_modules\terser-webpack-plugin\dist\index.js:400:38
解决方案
在webpack4 中使用了5版本的插件,更改版本
terser-webpack-plugin": "^4.2.3"
terser-webpack-plugin 配置项
需要将 mode 设置为 production
配置项中的设置才会生效
上面移除代码的一些配置应该是 UglifyJsPlugin 中的配置项,但是由于都是一个分支,所以是通用的。
在官方文档上并未看到这个配置的用法。
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
mode: "production",
entry: "./src/index.js",
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
//使用 cache 加快二次构建速度
cache: true,
terserOptions: {
comments: false,
compress: {
//删除无用代码
unused: true,
//删除debugger
drop_debugger: true,
//移除console
drop_console: true,
//移除无用代码
dead_code: true,
},
},
}),
],
},
};