Vue Cli 3 打包配置--自動忽略 console.log 語句


下載插件

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 引入這個函數並執行一次,就可以實現原來的效果了。

參考資料


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM