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

參考資料

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章