vite5打包时我只想清除console.log不想清除console.info该怎么配置?

vite5打包时我只想清除console.log不想清除console.info该怎么配置?

阅读 3.1k
avatarAI BotBETA

在Vite 5中,如果你想要在打包时仅清除console.log而不清除console.info,你可以通过修改terser插件的配置来实现。terser是Vite用于压缩和混淆代码的插件,它有一个drop_console选项可以用来控制是否移除所有的console相关调用。但是,terser并没有提供直接区分console.logconsole.info的功能。

不过,你可以通过自定义一个terser插件选项,使用compress中的pure_funcs来指定你想要移除的函数列表。在这个例子中,你可以只列出console.log,这样只有console.log调用会被移除,而console.info调用则会被保留。

以下是一个配置示例:

// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  build: {
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: false, // 禁用默认的移除所有console调用
        pure_funcs: ['console.log'], // 只移除console.log调用
      },
    },
  },
})

在这个配置中,drop_console被设置为false,以防止terser默认移除所有console调用。然后,pure_funcs被配置为仅包含console.log,这告诉terser只移除那些函数调用。

请注意,pure_funcs的配置只能移除那些被认定为“纯函数”的调用,也就是说,如果console.log被用在某个赋值操作中,或者其返回值被使用了,那么terser可能不会移除它,因为这样做可能会改变代码的行为。

另外,如果你使用的是vite的默认配置,并且没有显式地修改minifyterserOptions,你可以直接添加或修改vite.config.js中的build对象,以添加上述配置。

最后,请确保你的viteterser插件版本是最新的,以利用最新的功能和修复。

3 个回答

安装 terser:

npm install terser --save-dev

vite.config.js中增加代码:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue'
export default defineConfig({
   plugins: [vue()],
   build:{
      minify:"terser",
      terserOptions:{
        compress:{
          drop_console:true,
          pure_funcs: ['console.log']
        }
      }
    }
});
  • drop_console: true 会移除所有的 console.* 调用。
  • pure_funcs: ['console.log'] 会指定只移除 console.log,其他如 console.info, console.error 等则会被保留。

How to remove console.log ,when vite build use esbuild? #7920

上面的答主写的挺好。

但提问的这个小伙伴可能无法访问 github。我补充下代码~

export default defineConfig({
    esbuild: {
      drop: ['console', 'debugger'],
    },
});
export default defineConfig(({ mode }) => {
  return {
    // other configuration
    esbuild: {
      pure: mode === 'production' ? ['console.log'] : [],
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题