作者:王倩albe | 来源:互联网 | 2023-12-11 21:16
本文记录了在vuecli3.x中移除console的一些采坑经验,通过使用uglifyjs-webpack-plugin插件,在vue.config.js中进行相关配置,包括设置minimizer、UglifyJsPlugin和compress等参数,最终成功移除了console。同时,还包括了一些可能出现的报错情况和解决方法。
vue-cli 3.x 移除console总结
运用 uglifyjs-webpack-plugin
插件
设置以下:
// vue.config.js
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
module.exports = {
configureWebpack: {
optimization: {
minimizer: [
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false,
drop_console: true,//console
drop_debugger: false,
pure_funcs: ['console.log']//移除console
}
}
})
]
}
},
}
没胜利报错以下
$ vue-cli-service build
⠋ Building for production...
ERROR Failed to compile with 5 errors 11:19:57 AM
error
static/js/app.2cd76486.js from UglifyJs
Unexpected token: punc «(» [static/js/app.2cd76486.js:1,23125]
error
static/js/chunk-66db1624.14c7d3b2.js from UglifyJs
Unexpected token: punc «(» [static/js/chunk-66db1624.14c7d3b2.js:1,733956]
error
static/js/exception_403.5d780122.js from UglifyJs
Unexpected token: punc «(» [static/js/exception_403.5d780122.js:1,281]
error
static/js/exception_404.3457fc52.js from UglifyJs
Unexpected token: punc «(» [static/js/exception_404.3457fc52.js:1,281]
error
static/js/exception_500.94c7c527.js from UglifyJs
Unexpected token: punc «(» [static/js/exception_500.94c7c527.js:1,283]
ERROR Build failed with errors.
error Command failed with exit code 1.
设置optimization.minimizer
- 参考 vuecli3+webpack4优化实践(删除console.log和设置dllPlugin)
// vue.config.js
module.exports = {
chainWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
config.optimization.minimizer[0].options.terserOptions.compress.warnings = false
config.optimization.minimizer[0].options.terserOptions.compress.drop_cOnsole= true
config.optimization.minimizer[0].options.terserOptions.compress.drop_debugger = true
config.optimization.minimizer[0].options.terserOptions.compress.pure_funcs = ['console.log']
}
}
}
终究照样没有胜利,报错以下:
$ vue-cli-service build
⠋ Building for production... ERROR TypeError: Cannot read property 'options' of undefined
TypeError: Cannot read property 'options' of undefined
运用babel-plugin-transform-remove-console
插件
装置依靠库
$ npm install babel-plugin-transform-remove-console --save-dev
# or
$ yarn add babel-plugin-transform-remove-console --dev
【babel.config.js】设置以下
const plugins = ["@vue/babel-plugin-transform-vue-jsx"]
// 临盆环境移除console
if(process.env.NODE_ENV === 'production') {
plugins.push("transform-remove-console")
}
module.exports = {
plugins: plugins,
presets: [
[
'@vue/app', {
modules: false,
targets: {
browsers: ["> 1%", "last 2 versions", "not ie <= 8", "Android >= 4", "iOS >= 8"]
},
useBuiltIns: 'entry',
}
]
]
}
总结该计划胜利了