vitejs / vite

Next generation frontend tooling. It's fast!
http://vite.dev
MIT License
68.35k stars 6.16k forks source link

`vite:define` can't process `std-env` #15367

Closed danielroe closed 10 months ago

danielroe commented 10 months ago

Describe the bug

std-env contains some environment-agnostic utilities (see source).

The current vite:define plugin can't process this (see compiled library), and there seems to be no way to opt-out of processing a file with the define plugin.

Linked upstream issue: https://github.com/nuxt/nuxt/issues/24793

Reproduction

https://stackblitz.com/edit/vitejs-vite-ndari4

Steps to reproduce

npm run dev (which will run the build command)

System Info

StackBlitz

Used Package Manager

npm

Logs

No response

Validations

stackblitz[bot] commented 10 months ago

Fix this issue in StackBlitz Codeflow Start a new pull request in StackBlitz Codeflow.

hi-ogawa commented 10 months ago

It looks like esbuild's bug. I was testing https://unpkg.com/std-env@3.6.0/dist/index.mjs on esbuild playground with define picked from:

https://github.com/vitejs/vite/blob/5684fcd8d27110d098b3e1c19d851f44251588f1/packages/vite/src/node/plugins/define.ts#L19-L26

And I found that applying { define: { "globalThis.process.env": "{}" } } to the source code globalThis.process?.env[o] triggers a panic.

Here are playground links:

hi-ogawa commented 10 months ago

I just thought of the quick workaround to replace offending globalThis.process?.env[o] via plugin. This also verifies that the underlying issue is only this exact expression:

https://stackblitz.com/edit/vitejs-vite-k6fmaw?file=vite.config.ts

import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    {
      name: 'workaround-esbuild-define-panic',
      enforce: 'pre',
      transform(code) {
        return code.replace(
          'globalThis.process?.env[o]',
          '(globalThis.process?.env)[o]'
        );
      },
    },
  ],
});
hi-ogawa commented 10 months ago

This should be fixed in esbuild v0.19.10 https://github.com/evanw/esbuild/releases/tag/v0.19.10

I confirmed vite build succeeds on stackblitz via package.json "overrides": { "esbuild": "0.19.10" }

https://stackblitz.com/edit/vitejs-vite-21ssdn?file=package.json

sapphi-red commented 10 months ago

@hi-ogawa Thanks for investigating and the fix 💚