最可靠的方式是配置 build.rollupoptions.terseroptions.compress.drop_console: true,它在生产构建时由 terser 自动移除所有 console.* 调用,且不影响开发环境;需配合 drop_debugger: true 删除 debugger 语句,但无法处理动态执行的日志。

在 Vite 生产构建中移除所有 console 日志(如 console.log、console.warn、console.error 等),最可靠的方式是借助 Rollup 的 dropConsole 插件选项,因为 Vite 底层使用 Rollup 进行生产构建(vite build)。
配置 build.rollupOptions.terserOptions
Vite 通过 Terser 压缩 JavaScript,而 Terser 提供了 drop_console: true 选项,可自动删除所有 console.* 调用(包括带表达式的,如 console.log(a, b))。
在 vite.config.ts 或 vite.config.js 中添加:
export default defineConfig({
build: {
rollupOptions: {
// 仅在生产环境启用(vite build 时生效)
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
}
}
}
})
注意作用范围和限制
- 该配置只影响 最终打包输出的 JS 文件,不影响开发服务器(
vite dev)——开发时日志照常输出,符合预期。 -
drop_console: true会移除所有console.*调用,但不会移除debugger语句(需配合drop_debugger: true)。 - 它不处理字符串中的伪日志(如
eval("console.log(1)")或模板字符串拼接),这类属于动态执行,Terser 无法安全删除。 - 若你使用了自定义日志工具(如
loglevel、winston),需额外配置其 production 模式或用 define 替换。
补充:用 define 配合条件日志(更可控)
对于需要精细控制(比如保留 console.error 但删掉 log 和 warn),可结合 Vite 的 define 宏替换:
export default defineConfig({
define: {
__DEV__: JSON.stringify(!process.env.PROD),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production')
},
build: {
rollupOptions: {
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
}
}
}
})
然后在代码中写:
if (__DEV__) {
console.log('debug info')
}
Terser 在压缩时能识别并移除整个 if (false) { ... } 块(前提是 __DEV__ 是字面量布尔值),比单纯 drop_console 更安全灵活。
验证是否生效
- 运行
vite build后检查dist/下生成的 JS 文件,搜索console.确认无残留。 - 也可在构建后打开浏览器开发者工具 → Sources → 找到对应 chunk,查看压缩后代码是否已剔除。
- 注意:若用了 source map(
build.sourcemap: true),源码里仍可见日志,但实际运行的代码中已不存在。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











