motdotla / dotenv-expand

Variable expansion for dotenv. Expand variables already on your machine for use in your .env file.

Home Page:https://dotenvx.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

cannot use while using dotenv.parse

rubiin opened this issue · comments

the sample tells us to use dotenv.config however i am using dot.parse function instead. How to load expanded variables in that approach

@rubiin You can easily work around that limitation, mimicking dotenv.config's structure:

async function loadEnv(): Config {
  const rawEnv = await loadEnvFile();

  const parsed = dotenv.parse(rawEnv);
  const expandedEnv = dotenvExpand({ parsed } as any);

  return expandedEnv.parsed as unknown as Config;
}

lemme try

The provided suggestion doesn't work:

.env

NODE_ENV=test
BASIC=basic
BASIC_EXPAND=$BASIC
MACHINE=machine_env
MACHINE_EXPAND=$MACHINE

script:

const parsedEnv = dotenv.parse(fs.readFileSync(path.join(__dirname, envFilepath)));
console.log("Parsed", parsedEnv);
const expandedEnv = dotenvExpand({parsedEnv});
console.log("Expanded", expandedEnv);

result:

Parsed {
  NODE_ENV: 'test',
  BASIC: 'basic',
  BASIC_EXPAND: '$BASIC',
  MACHINE: 'machine_env',
  MACHINE_EXPAND: '$MACHINE'
}
Expanded {
  parsedEnv: {
    NODE_ENV: 'test',
    BASIC: 'basic',
    BASIC_EXPAND: '$BASIC',
    MACHINE: 'machine_env',
    MACHINE_EXPAND: '$MACHINE'
  }
}

node v14.17.5
dotenv 10.0.0
dotenv-expand 5.1.0

Alright, config.parsed is hardcoded.

Here's a working function I'm using in a google zx script:

const overrideEnvironment = (envFilepath) => {
  const parsed = dotenv.parse(fs.readFileSync(path.join(__dirname, envFilepath)));
  const expanded = dotenvExpand({parsed});
  for (const k in expanded.parsed) {
    process.env[k] = expanded.parsed[k];
  }
}