下載插件
npm i -D uglifyjs-webpack-plugin
在 vue.config.js 引入使用
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
configureWebpack: {
plugins: [
new UglifyJsPlugin({
uglifyOptions: {
compress: {
drop_console: true,
},
},
}),
],
},
devServer: {
proxy: {
'/xxx': {
target: 'http://192.168.150.17:8080/',
changeOrigin: true,
ws: true,
pathRewrite: {
'^/xxx': 'xxx',
},
},
},
},
publicPath: './',
}
這時執行 npm run build
打包后的文件就沒有 console.log
語句了。
不過這時會有一個問題,就是在開發環境的時候編譯會非常慢。例如修改了一個變量的值,我的電腦要編譯 10 秒才能重新刷出來頁面,一直卡在 92% chunk asset optimization
。
由於去掉 console.log
語句這個功能只有在打包時才需要,所以我們可以加一個判斷,只在生產環境時才把上述配置代碼加上。
所以正確的配置如下:
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const config = {
devServer: {
proxy: {
'/xxx': {
target: 'http://192.168.150.17:8080/',
changeOrigin: true,
ws: true,
pathRewrite: {
'^/xxx': 'xxx',
},
},
},
},
publicPath: './',
}
if (process.env.NODE_ENV === 'production') {
config.configureWebpack = {
plugins: [
new UglifyJsPlugin({
uglifyOptions: {
compress: {
drop_console: true,
},
},
}),
],
}
}
module.exports = config
2020.8.5 更新
使用上述方法有個缺陷,就是每次打包的時間太長。現在我已經棄用這種方法了,改成重寫 console.log()
函數,效果更好,具體代碼如下:
export function rewirteLog() {
console.log = (function (log) {
return process.env.NODE_ENV == 'development'? log : function() {}
}(console.log))
}
在 main.js
引入這個函數並執行一次,就可以實現原來的效果了。