在 vite 项目中去除 console 日志,核心配置是在 `vite.config.js` 中启用 `build.minify` 并传入 `terser` 选项,设置 `compress.drop_console` 为 true。这样 vite 会在构建压缩阶段调用 terser 工具,自动剥离代码中的 console 语句。需要注意的是,如果项目使用了 `esbuild` 作为默认压缩器,该配置可能不生效,此时需显式指定使用 terser。

Vite 默认压缩器 esbuild 是否支持 drop_console
不支持。Vite 默认使用 esbuild 进行生产环境压缩,而 esbuild 目前尚未实现 drop_console 功能。因此,仅依赖 Vite 默认配置无法去除 console 日志,必须切换至 terser 或手动处理。

import { defineConfig } from 'vite';
import terserPlugin from '@rollup/plugin-terser';
export default defineConfig({
build: {
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
},
},
},
plugins: [terserPlugin()],
});
运行 npx vite build 后,检查输出文件,确认 console.log 等语句已被移除。预期结果:构建产物中不再包含任何 console 相关代码,且应用正常运行。
立即学习“Java免费学习笔记(深入)”;
Terser 配置 drop_console 的具体参数与效果
Terser 的 drop_console 参数是一个布尔值,设为 true 时,会删除所有 console 调用。若需更精细控制,可使用 pure_funcs 指定要删除的函数名列表。例如,仅删除 console.log 而保留 console.warn,可配置 pure_funcs: ['console.log']。此配置适用于需要保留部分调试信息的场景。

// 测试代码
console.log('debug');
console.warn('warning');
console.error('error');
// 预期输出(构建后)
// console.log 被移除
// console.warn 和 console.error 保留
通过调整 pure_funcs,可实现对 console 调用的选择性删除。验证方法:构建后检查产物,确认仅删除了指定的 console 函数调用。此方法比全局 drop_console 更灵活,适合复杂项目需求。
基于程序中 console.log 输入的条件判断问题
当程序中存在条件分支如 if (process.env.NODE_ENV === 'production') { console.log(...) } 时,Terser 的 drop_console 仍会删除该语句,因为它是静态分析可识别的调用。即使条件为 false,只要语法上是 console 调用,就会被移除。若需保留特定 console 调用,应使用 pure_funcs 排除,或改用其他日志机制如自定义 logger 函数。


















