vue3取消debug模式下的log

338 阅读1分钟

开发模式下我们都喜欢打各种log,但是生产模式下log是不应该存在的。

这里我使用了两种方案供大家参考:

1. 使用terser

  1. 在终端输入npm install terser -g
  2. vite.config.js中添加build配置,如下:

import { defineConfig } from "vite"

export default defineConfig({
  
  build: {
    // start
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
    // end
  },
})

如此这般,打包之后所有的console.log就不会在打印了。

2. 手动重写log

这种方案不需要使用插件。直接在main.js入口文件这里重写即可。

    if (import.meta.env.MODE === 'production') {
      window.console.log = function () { }
    }

判断为import.meta.env.MODE === 'production'生产环境,就重写console.log方法,以达到清理开发阶段打印的需求。