Support missing import.meta.env
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;
}
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.
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).
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?).
Don't mind at all, but will only be able to do that in a week.
So with Vite 3 and https://github.com/vitejs/vite/issues/8663 not fixed, even this PR doesn't fix building storybooks ¯\_(ツ)_/¯