Skip to content

feat: support dotenv.override #190

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/dotenv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ export interface DotenvOptions {
*/

env?: NodeJS.ProcessEnv;

/**
* When set to `true`, any existing environment variables will be overridden.
* Defaults to `false`.
*/
override?: boolean;
}

export type Env = typeof process.env;
Expand All @@ -49,12 +55,15 @@ export async function setupDotenv(options: DotenvOptions): Promise<Env> {
fileName: options.fileName ?? ".env",
env: targetEnvironment,
interpolate: options.interpolate ?? true,
override: options.override ?? false,
});

// Fill process.env
for (const key in environment) {
if (!key.startsWith("_") && targetEnvironment[key] === undefined) {
targetEnvironment[key] = environment[key];
if (!key.startsWith("_")) {
if (options.override || targetEnvironment[key] === undefined) {
targetEnvironment[key] = environment[key];
}
}
}

Expand All @@ -74,7 +83,15 @@ export async function loadDotenv(options: DotenvOptions): Promise<Env> {

// Apply process.env
if (!options.env?._applied) {
Object.assign(environment, options.env);
if (options.override && options.env) {
for (const key in options.env) {
if (!(key in environment) && !key.startsWith("_")) {
environment[key] = options.env[key];
}
}
} else {
Object.assign(environment, options.env);
}
environment._applied = true;
}

Expand Down