Skip to content

Commit

Permalink
Feature: replace environmental variable with in binary expression (#7954
Browse files Browse the repository at this point in the history
)
  • Loading branch information
Shinyaigeek committed Apr 21, 2022
1 parent 03ec6d1 commit f29c181
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
@@ -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
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
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

0 comments on commit f29c181

Please sign in to comment.