vite
vite copied to clipboard
import.meta.env is undefined when used in ternary operator following a spread
Describe the bug
when import.meta.env
is used in a ternary operator, following an array spread, vite can't seem to pick up import.meta.env
is being used, and it becomes undefined.
E.g.
const v = [...(import.meta.env ? [true] : [false])]
will result in error:
Uncaught TypeError: Cannot read properties of undefined (reading 'DEV')
However without the ...
spread seems to work ok.
const v = import.meta.env ? [true] : [false]
Please see the reproduction link.
Reproduction
https://stackblitz.com/edit/vitejs-vite-7mr8pa
Steps to reproduce
No response
System Info
System:
OS: Linux 5.0 undefined
CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
Memory: 0 Bytes / 0 Bytes
Shell: 1.0 - /bin/jsh
Binaries:
Node: 16.14.2 - /usr/local/bin/node
Yarn: 1.22.19 - /usr/local/bin/yarn
npm: 7.17.0 - /usr/local/bin/npm
npmPackages:
vite: 4.0.4 => 4.0.4
Used Package Manager
npm
Logs
No response
Validations
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guidelines.
- [X] Read the docs.
- [X] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- [X] Make sure this is a Vite issue and not a framework-specific issue. For example, if it's a Vue SFC related bug, it should likely be reported to vuejs/core instead.
- [X] Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- [X] The provided reproduction is a minimal reproducible example of the bug.
This seems to be a bug in es-module-lexer
: https://github.com/guybedford/es-module-lexer/issues/145
const v = [...(import.meta.env ? [true] : [false])]
is transformed to
const v = [...import.meta.env ? [true] : [false]]
by esbuild (this transformation is valid). Then, it faces that bug.
For a workaround, split it into two variables. This will avoid ...import.meta
to be there.
const d = import.meta.env.DEV ? [true] : [false];
const s = [...d];
The bug is fixed in es-module-lexer now, but it introduces a regression at https://github.com/guybedford/es-module-lexer/issues/148 so we can't bump it yet.
Closing as #12230 is merged.
🙌🙌 cheers to everyone who worked on this