env-var icon indicating copy to clipboard operation
env-var copied to clipboard

Don't default export `from(process.env)` for environments that don't have `process`

Open smblee opened this issue 2 years ago • 2 comments

Trying to use this lib with vite which uses import.meta.env as the default location for env vars and I get the following error

process is not defined
    at node_modules/env-var/env-var.js (env-var.js:55:23)

and looks like it's happening because the module exports from(process.env) by default and its failing since process doesn't actually exist within the vite environment i am in (sveltekit). https://github.com/evanshortiss/env-var/blob/3f5689ed13b307e4389b7dcf642bac55738e534c/env-var.js#L55

The code:

import { from } from 'env-var';

const env = from(import.meta.env);

export const API_BASE_URL = env.get('VITE_API_BASE_URL').required().asUrlString();

smblee avatar Jul 06 '22 18:07 smblee

Thanks for raising this issue @smblee. I think it's a good point, and the module probably shouldn't assume that it's operating in a Node.js environment.

One problem is that I think this will break backwards compatibility, unless the code is changed to use some sort of conditional check.

If you change the line causing the issue to this, does it fix the issue?

module.exports = from(typeof process === 'undefined' ? {} : process.env) 

evanshortiss avatar Jul 06 '22 19:07 evanshortiss

@smblee any luck with that fix? If so I can merge it into this module and push a patch release.

evanshortiss avatar Jul 07 '22 18:07 evanshortiss

This is available in the beta release of version 8. You can install and test it using npm install env-var@beta. Feel free to reopen this issue if necessary.

EDIT: See my latest comment in this thread for a fix with v7.x

evanshortiss avatar Dec 25 '22 04:12 evanshortiss

hi @evanshortiss , thanks for your work on this! Wanted to let you know that the beta worked just fine in my Vite React app -- head's up to anyone reading this, I had to place import.meta.env in an object like so:

const env = from({ variables: import.meta.env });

CassandraNewell avatar Jun 13 '23 13:06 CassandraNewell

@evanshortiss May I ask when you will release the beta version?

kenberkeley avatar Aug 18 '23 10:08 kenberkeley

@kenberkeley I have released v7.4.0 with this fix. You can now do the following for Vite environments:

const env = from(import.meta.env);

Or in React with create-react-app, you need to explicitly reference each variable like:

const env = from({
  SOME_VARIABLE: process.env.REACT_APP_SOME_VARIABLE
});

evanshortiss avatar Aug 21 '23 19:08 evanshortiss