devserver配置_Vue Cli 3 打包配置--自动忽略 console.log 语句

2760a2cb17acc82c4e7e0f330c53afc2.png

下载插件

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 引入这个函数并执行一次,就可以实现原来的效果了。

参考资料

  • uglifyjs-webpack-plugin
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值