builder-vite icon indicating copy to clipboard operation
builder-vite copied to clipboard

Support missing import.meta.env

Open princed opened this issue 3 years ago • 5 comments

Currently vite storybook builder breaks when any env var used in code via import.meta.env is missing while building storybooks.

Apparently that happens because Rollup does direct inline replacements and turns code like

const getMyVar = () => import.meta.env.VITE_MISSING_VAR === 'true'

into something like

const getMyVar = () => {"BASE_URL":"/","MODE":"production","DEV":false,"PROD":true}.VITE_MISSING_VAR === "true";

which is syntactically incorrect. See my reproduction repo for an example — https://github.com/princed/vite-sb-meta-env-repro.

To mitigate this vite itself adds a replacement from import.meta.env. to ({}). to catch missing direct replacements and produce correct code. I opted for identical solution here.

A similar workaround is also possible on the user side:

viteFinal(config) {
   config.define = {
     'import.meta.env.': `({}).`,
   };
   return config; 
}

princed avatar Jun 20 '22 07:06 princed

Thanks for this PR. It seems like maybe the vite solution still has a kink to work out? https://github.com/vitejs/vite/issues/8663. Maybe we should hold off until that issue is solved, before adding this.

IanVS avatar Jun 21 '22 20:06 IanVS

It seems like maybe the vite solution still has a kink to work out? https://github.com/vitejs/vite/issues/8663. Maybe we should hold off until that issue is solved, before adding this.

Happy to wait and see whether Vite team finds another approach to the problem, but it seems unlikely though. We also could just merge this for now, and then handle changes (if any) when adding Vite 3 support (which will surely require some dedicated effort).

princed avatar Jun 22 '22 03:06 princed

Vite 3 has been released, and https://github.com/vitejs/vite/issues/8663 is not yet solved. I'm happy to proceed with this if the underlying problem is still an issue in Vite 3 (would you mind confirming?).

IanVS avatar Jul 15 '22 15:07 IanVS

Don't mind at all, but will only be able to do that in a week.

princed avatar Jul 17 '22 11:07 princed

So with Vite 3 and https://github.com/vitejs/vite/issues/8663 not fixed, even this PR doesn't fix building storybooks ¯\_(ツ)_/¯

princed avatar Jul 24 '22 01:07 princed