Vuecli项目上线——使用 transform-remove-console

问题描述

当项目开发完成,打包上线时Vue报错:Unexpected console statement (no-console),这是因为在发布项目时 ESLint 不允许使用 console

解决方法

方法一

在配置文件eslintrc.js中增加规则'no-console': [true, 'log', 'error']

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: ['plugin:vue/essential', '@vue/standard'],
  parserOptions: {
    parser: 'babel-eslint'
  },
  rules: {
    indent: ['off', 2],
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'space-before-function-paren': 0,
    'no-console': [true, 'log', 'error'],
    semi: 0
  }
}

这样虽然能够正常打包,但是实际部署时最好是不要出现 console.

方法二

使用依赖 babel-plugin-transform-remove-console

搜索安装依赖后在配置文件babel.config.js中引用


module.exports = {
  presets: ['@vue/cli-plugin-babel/preset'],
  plugins: [
    [
      'component',
      {
        libraryName: 'element-ui',
        styleLibraryName: 'theme-chalk'
      }
    ],
    'transform-remove-console'
  ]
}

这样做虽然能解决问题,但在开发阶段 console 也会被删除,不方便开发调试,这里介绍方法三

方法三

使用依赖 babel-plugin-transform-remove-console

搜索安装依赖后在配置文件babel.config.js中引用

// 这是项目发布阶段需要用到的 babel 插件
const prodPlugins = []
// 判断当前为开发阶段 development 还是发布阶段  production
if (process.env.NODE_ENV === 'production') {
  prodPlugins.push('transform-remove-console')
}
 
module.exports = {
  presets: ['@vue/cli-plugin-babel/preset'],
  plugins: [
    [
      'component',
      {
        libraryName: 'element-ui',
        styleLibraryName: 'theme-chalk'
      }
    ],
    // 发布产品时候的插件数组,...表示展开运算符,意思是将数组里的每一项展开
    ...prodPlugins
  ]
}

这样就能只在发布阶段删除 console ,开发阶段不受影响

出处: https://catbk.cn/transform-remove-console.html


版权声明:本文为weixin_42322529原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。