在Vite 5 中,如果你希望在构建时只移除 console.log
,而保留其他 console
信息(如 console.warn
、console.error
等),你可以使用 babel-plugin-transform-remove-console
插件,并对其进行配置。
安装 babel-plugin-transform-remove-console
插件:
首先,你需要安装这个 Babel 插件:
npm install babel-plugin-transform-remove-console --save-dev
配置 Babel 插件:
接下来,你需要在 babel.config.js
或 vite.config.js
中配置这个插件,使其只移除 console.log
。
如果你使用的是 vite.config.js
,可以这样配置:
import { defineConfig } from 'vite';
import babel from 'vite-plugin-babel';
export default defineConfig({
plugins: [
babel({
babelConfig: {
plugins: [
['transform-remove-console', { exclude: ['error', 'warn', 'info'] }]
]
}
})
]
});
在这个配置中,exclude
选项指定了哪些 console
方法不会被移除。这里我们保留了 console.error
、console.warn
和 console.info
。
构建项目:
配置完成后,运行 vite build
命令进行构建:
npm run build
在构建过程中,console.log
会被移除,而其他 console
信息会被保留。
transform-remove-console
插件:这个插件可以移除所有的 console
调用。通过配置 exclude
选项,你可以指定哪些 console
方法不被移除。
vite-plugin-babel
:Vite 本身并不直接支持 Babel 插件,因此你需要使用 vite-plugin-babel
来集成 Babel 插件。
如果你使用的是 TypeScript,确保你的 tsconfig.json
中的 compilerOptions.target
设置为 ES6
或更高版本,因为 transform-remove-console
插件依赖于 ES6 的语法特性。
如果你在开发环境中也希望移除 console.log
,可以在 vite.config.js
中根据环境变量进行条件配置。
通过这种方式,你可以在 Vite 5 的构建过程中只移除 console.log
,而保留其他 console
信息。