vite5打包时我只想清除console.log不想清除console.info该怎么配置?
vite5打包时我只想清除console.log不想清除console.info该怎么配置?
在Vite 5中,如果你想要在打包时仅清除console.log
而不清除console.info
,你可以通过修改terser
插件的配置来实现。terser
是Vite用于压缩和混淆代码的插件,它有一个drop_console
选项可以用来控制是否移除所有的console
相关调用。但是,terser
并没有提供直接区分console.log
和console.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
的默认配置,并且没有显式地修改minify
和terserOptions
,你可以直接添加或修改vite.config.js
中的build
对象,以添加上述配置。
最后,请确保你的vite
和terser
插件版本是最新的,以利用最新的功能和修复。
安装 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']
}
}
}
});
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'] : [],
}
}
}
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
3 回答3.2k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
How to remove console.log ,when vite build use esbuild? #7920