(文章目录)
一、前言
Vue
项目开发过程中,会经常需要使用console.log
、console.info
、alert
等测试语句来输出内容,而在生产环境之中,我们不希望控制台同样输出以上信息,特别是用户信息相关。
组包前,逐一去删除、注释显然费时费力,好在Vue
提供了通过配置文件修改配置变量,实现在开发环境打印,而生产环境不打印控制台信息的方法。
二、配置文件修改
修改build/webpack.prod.conf.js
配置文件,找到UglifyJsPlugin
配置,在compress
中添加如下代码即可。
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false,
// 打包的时候移除console、debugger
drop_debugger: true, // 移除debugger
drop_console: true, // 移除console
pure_funcs: ['console.log','console.info']
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
更优的配置方式如下:
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false,
// 打包的时候移除console、debugger
drop_debugger: process.env.NODE_ENV=== 'production', // 移除debugger
drop_console: process.env.NODE_ENV=== 'production', // 移除console
warnings: process.env.NODE_ENV=== 'production', // 移除告警信息
pure_funcs: ['console.log','console.info']
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
其中,process.env.NODE_ENV
定义在prod.env.js
文件中,
module.exports = {
NODE_ENV: "production"
}
prod.env.js
文件在config/index.js
的build.env
配置中引入。
build: {
env: require('./prod.env')
}
三、拓展阅读
- 《[Vue2合集]》