在Vite 5项目构建过程中,开发者经常需要移除调试用的console.log语句,但又希望保留console.info等其它日志方法。本文将详细介绍三种专业解决方案。
// vite.config.js
export default defineConfig({
build: {
minify: 'terser',
terserOptions: {
compress: {
pure_funcs: ['console.log'] // 只移除console.log
}
}
}
})
安装必要依赖:
npm install @babel/core babel-plugin-transform-remove-console --save-dev
创建自定义插件:
// customBabelPlugin.js
module.exports = function() {
return {
visitor: {
CallExpression(path) {
if (path.node.callee.object?.name === 'console' &&
path.node.callee.property?.name === 'log') {
path.remove()
}
}
}
}
}
安装专用插件:
npm install vite-plugin-remove-console --save-dev
配置插件:
// vite.config.js
import removeConsole from 'vite-plugin-remove-console'
export default defineConfig({
plugins: [
removeConsole({
includes: ['log'] // 只移除log
})
]
})
通过以上方法,您可以精准控制Vite 5构建过程中console语句的处理方式,既保持代码整洁又不丢失重要调试信息。