vite icon indicating copy to clipboard operation
vite copied to clipboard

import.meta.env is undefined when used in ternary operator following a spread

Open ycmjason opened this issue 1 year ago • 1 comments

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

ycmjason avatar Jan 24 '23 13:01 ycmjason

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];

sapphi-red avatar Jan 24 '23 15:01 sapphi-red

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.

bluwy avatar Feb 23 '23 12:02 bluwy

Closing as #12230 is merged.

sapphi-red avatar Feb 28 '23 11:02 sapphi-red

🙌🙌 cheers to everyone who worked on this

ycmjason avatar Feb 28 '23 12:02 ycmjason