Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: replace environmental variable with in binary expression #7954

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const existVar = 'ABC' in process.env ? 'correct' : 'incorrect';
const notExistVar = 'DEF' in process.env ? 'incorrect' : 'correct';

module.exports = {
existVar,
notExistVar,
};
23 changes: 23 additions & 0 deletions packages/core/integration-tests/test/javascript.js
Original file line number Diff line number Diff line change
Expand Up @@ -3081,6 +3081,29 @@ describe('javascript', function () {
});
});

it('should inline environment variables with in binary expression whose right branch is process.env and left branch is string literal', async function () {
let b = await bundle(
path.join(__dirname, '/integration/env-binary-in-expression/index.js'),
{
env: {ABC: 'any'},
defaultTargetOptions: {
engines: {
browsers: '>= 0.25%',
},
},
},
);

let contents = await outputFS.readFile(b.getBundles()[0].filePath, 'utf8');
assert(!contents.includes('process.env'));

let output = await run(b);
assert.deepEqual(output, {
existVar: 'correct',
notExistVar: 'correct',
});
});

it('should insert environment variables from a file', async function () {
let b = await bundle(
path.join(__dirname, '/integration/env-file/index.js'),
Expand Down
15 changes: 15 additions & 0 deletions packages/transformers/js/core/src/env_replacer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,21 @@ impl<'a> Fold for EnvReplacer<'a> {
}
}

// Replace `'foo' in process.env` with a boolean.
match &node {
Expr::Bin(binary) if binary.op == BinaryOp::In => {
if let (Expr::Lit(Lit::Str(left)), Expr::Member(member)) = (&*binary.left, &*binary.right) {
if match_member_expr(member, vec!["process", "env"], self.decls) {
return Expr::Lit(Lit::Bool(Bool {
value: self.env.contains_key(&left.value),
span: DUMMY_SP,
}));
}
}
}
_ => {}
}

if let Expr::Member(ref member) = node {
if self.is_browser && match_member_expr(member, vec!["process", "browser"], self.decls) {
return Expr::Lit(Lit::Bool(Bool {
Expand Down