stackblitz / webcontainer-core

Dev environments. In your web app.
https://webcontainers.io
MIT License
3.94k stars 174 forks source link

Cannot reliably read process.env #1504

Closed chenyan-dfinity closed 2 months ago

chenyan-dfinity commented 2 months ago

Describe the bug

I'm running webpack 5 inside the web container, and passed in environment variable MYFLAG. The source code uses process.env.MYFLAG to read the environment variable. In webpack.config.js, I can correctly read the MYFLAG value. But in src/index.js, process.env.MYFLAG is sometimes undefined, and sometimes the correct value. The result of process.env.MYFLAG in the bundled code is unpredictable. I tried to read pre-defined variables like process.env.HOME, the result is the same.

Link to the blitz that caused the error

https://stackblitz.com/edit/stackblitz-webcontainer-api-starter-fapmje?file=files.js

Steps to reproduce

  1. Go to the stackblitz link
  2. See the preview window and console log.
  3. During running webpack, MYFLAG is correctly printed to console log.
  4. The preview window on the right shows: "flag: undefined", which should be "flag: PASSED_IN_FLAG"
  5. Rerun this at different times, the preview window can sometimes show the expected result.

Expected behavior

webpack should read process.env reliably for bundled code

Parity with Local

Screenshots

No response

Platform

No response

Additional context

No response

chenyan-dfinity commented 2 months ago

I have another repo with vite's import.meta.env. It's the same problem: https://stackblitz.com/edit/stackblitz-webcontainer-api-starter-hypsww?file=files.js

Nemikolh commented 2 months ago

Hey @chenyan-dfinity! Thanks for the report!

I'm not sure about webpack but for vite, the environment variable is only exposed to the client if it starts with VITE_.

Trying your vite example with a variable starting with VITE_ seems to work: https://stackblitz.com/edit/stackblitz-webcontainer-api-starter-umcn6j

chenyan-dfinity commented 2 months ago

Thanks. I can confirm everything is working as expected. The problem was caused by something else in my code.

Nemikolh commented 2 months ago

No problem! Thanks for double-checking and closing this issue :pray: