Skip to content

Instantly share code, notes, and snippets.

@tanishqmanuja
Created April 20, 2024 15:14
Show Gist options
  • Save tanishqmanuja/56aed05b4d6d1370cb3f5d27b4620671 to your computer and use it in GitHub Desktop.
Save tanishqmanuja/56aed05b4d6d1370cb3f5d27b4620671 to your computer and use it in GitHub Desktop.
Load ENV file bun style.
import * as dotenv from "dotenv";
export const DEFAULT_ENV_FILE_MAP = {
production: ".env.production",
development: ".env.development",
test: ".env.test",
};
type Config = Record<string, string | false | undefined>;
type ConfigFn = (defaultFilemap: Config) => Config;
/**
* Replicate bun's behavior of loading .env files in the following order by default:
* - .env
* - .env.production, .env.development, .env.test (depending on NODE_ENV, default is development)
* - .env.local
*
* @link https://bun.sh/docs/runtime/env
*/
export function load(config: Config | ConfigFn = DEFAULT_ENV_FILE_MAP): void {
if (process.versions.bun || process.execArgv.includes("--env-file")) {
return;
}
dotenv.config();
const c =
typeof config === "function" ? config(DEFAULT_ENV_FILE_MAP) : config;
const path = c[process.env.NODE_ENV ?? "development"];
if (path) {
dotenv.config({ path, override: true });
}
dotenv.config({ path: ".env.local", override: true });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment