项目开发稳定,后期上生产环境的时候,需要进行性能优化,删除开发环境的控制台打印消息是优化中的一项,基于
webpack打包的项目可以使用terser-webpack-plugin,本文对该插件配置过程进行记录。
说明
webpack 4之前使用的可实现相同功能的uglifyjs-webpack-plugin插件已废弃;terser-webpack-plugin支持webpack4与5版本;- devtool 的 source maps仅支持以下选项:
source-map,inline-source-map,hidden-source-map以及nosources-source-map values。
安装
首先将terser-webpack-plugin 安装到项目的 dev 依赖中
npm install terser-webpack-plugin --save-dev
yarn add -D terser-webpack-plugin
pnpm add -D terser-webpack-plugin
配置
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
// ...webpack config,
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
},
format: {
comments: false
}
},
extractComments: false
})
],
// ...otherOptions
}
}
验证
打包并发布到生产环境后,查看浏览器控制台发现浏览器console空空如也!