要在babel.config.js中使用环境变量,可以按照以下步骤操作:
MY_ENV=production
npm install dotenv --save-dev
config()方法加载.env文件中的环境变量。例如,可以像这样修改babel.config.js文件:require('dotenv').config();
module.exports = function(api) {
// 配置文件的其余部分
}
module.exports = function(api) {
const isProduction = process.env.MY_ENV === 'production';
const plugins = [
// 根据环境变量配置插件
isProduction && 'transform-remove-console',
].filter(Boolean);
return {
presets: [
// 根据环境变量配置预设
isProduction && '@babel/preset-env',
].filter(Boolean),
plugins,
};
}
在上面的示例中,根据MY_ENV环境变量的值,如果是"production",则会使用transform-remove-console插件和@babel/preset-env预设。
通过这种方式,您可以在babel.config.js中根据环境变量动态配置babel插件、预设等。