diff --git a/packages/core/integration-tests/test/integration/env-binary-in-expression/index.js b/packages/core/integration-tests/test/integration/env-binary-in-expression/index.js new file mode 100644 index 00000000000..5523e8b2acf --- /dev/null +++ b/packages/core/integration-tests/test/integration/env-binary-in-expression/index.js @@ -0,0 +1,7 @@ +const existVar = 'ABC' in process.env ? 'correct' : 'incorrect'; +const notExistVar = 'DEF' in process.env ? 'incorrect' : 'correct'; + +module.exports = { + existVar, + notExistVar, +}; diff --git a/packages/core/integration-tests/test/javascript.js b/packages/core/integration-tests/test/javascript.js index 3f85fdeb344..ff23790cba6 100644 --- a/packages/core/integration-tests/test/javascript.js +++ b/packages/core/integration-tests/test/javascript.js @@ -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'), diff --git a/packages/transformers/js/core/src/env_replacer.rs b/packages/transformers/js/core/src/env_replacer.rs index 761cb3e2184..421370248ab 100644 --- a/packages/transformers/js/core/src/env_replacer.rs +++ b/packages/transformers/js/core/src/env_replacer.rs @@ -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 {