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

define process.env.NODE_ENV works differently #2719

Closed
sapphi-red opened this issue Dec 7, 2022 · 4 comments
Closed

define process.env.NODE_ENV works differently #2719

sapphi-red opened this issue Dec 7, 2022 · 4 comments

Comments

@sapphi-red
Copy link
Contributor

sapphi-red commented Dec 7, 2022

process.env.NODE_ENV = 'test'
const foo = process.env.NODE_ENV

foo.bar = 'foo bar'
const bar = foo.bar

is transformed to

"node_env" = "test"; // process.env.NODE_ENV is replaced even if it's a lvalue
const foo = "node_env";
foo.bar = "foo bar"; // foo.bar is not replaced
const bar = foo.bar;

with --define:process.env.NODE_ENV=\"node_env\" --define:foo.bar=\"foo_bar\" (repl).

The generated code is not a valid code. A string cannot be a lvalue.

This happens with 0.11.23, 0.12.29, 0.13.15, 0.14.54, 0.15.18, 0.16.1.

@evanw
Copy link
Owner

evanw commented Dec 7, 2022

I just looked into this. There isn't anything special about process.env.NODE_ENV here. In your example the define for foo.bar doesn't apply because the define feature only replaces global variable references and foo is a local variable in this case. If you add let process to the code then process.env.NODE_ENV won't be replaced either, since then process will also be a local variable.

@sapphi-red
Copy link
Contributor Author

Oh, you are right. There aren't anything special with process.env.NODE_ENV. It's special when it includes a ..

foo_bar = 'foo bar'
const bar = foo_bar

is transformed to

foo_bar = "foo bar";
const bar = "foo_bar";

@evanw
Copy link
Owner

evanw commented Dec 7, 2022

I discovered that Webpack's DefinePlugin has the same behavior here (being able to replace an assignment target with a non-identifier). I can change esbuild to avoid generating code with a syntax error by avoiding replacements for assignment targets, but the result still won't make much sense since it means the load will be substituted but the store won't be.

Edit: Maybe that means it's a good candidate for a warning. I should probably add one for this case (define for something in assignment position).

@sapphi-red
Copy link
Contributor Author

I agree the result won't make sense. This is something I found while digging around #2718.
I think it's nice to have a warning.

@evanw evanw closed this as completed in 9493e3b Dec 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants