当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vue Cli3 打包配置并自动忽略console.log语句的方法

Vue Cli3 打包配置并自动忽略console.log语句的方法

2020年05月10日  | 移动技术网IT编程  | 我要评论

如何学英语,大厂生活网,二十四香谱图解

下载插件

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

vue-cli3.0 生产包去除console.log

不安装插件去除console.log的方法

vue-cli3.0在打包过程中就使用了terser-webpack-plugin插件进行优化,具体配置可以node_modules/@vue/cli-service/lib/config/prod.js中看到。

这里使用了环境变量进行控制,只有打生产包的时候才会调用这个插件进行打包优化。

terser-webpack-plugin的具体配置在同一个文件夹下terseroptions.js中,只要在这个文件中compress对象中加入以下几个属性就可以了

warnings: false,
drop_console: true,
drop_debugger: true,
pure_funcs: ['console.log']

到此这篇关于vue cli3 打包配置并自动忽略console.log语句的方法的文章就介绍到这了,更多相关vue cli3打包并忽略console.log内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网