一:webpack可实现需求
生产环境下删除console的好处如下:
- 显得更加专业、规范;
- 提升首屏加载速度
通过给webpack安装插件,可实现打包出来的版本,没有console和debugger。开发环境下还保留console/debugger,既保证开发时方便,又不影响生产版本。
二:实现步骤
1、安装 uglifyjs-webpack-plugin
npm install uglifyjs-webpack-plugin
2、config.js配置
configureWebpack:config=>{
// build时关闭console、debugger
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
config.plugins.push(
new UglifyJsPlugin({
uglifyOptions: {
compress: {
drop_debugger: true,//关闭debug
drop_console: true,//关闭console
}
},
})
);
}
三:问题解决
如果报错,如下:
! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] serve: vue-cli-service serve
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] serve script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Admin\AppData\Roaming\npm-cache_logs\2023-02-06T14_17_03_399Z-debug.log
删掉依赖node_modules,重新安装即可
四:效果对比
我的博客,生产版本console干干净净,如下:生产版本
代码在开发环境,npm run serve,可看到各种console和debugger。
源码如下:github地址