|
| 1 | +import path from "path"; |
| 2 | +import { normalize } from "path"; |
| 3 | +// eslint-disable-next-line |
| 4 | +import { loadEnvFile } from "process"; |
| 5 | + |
| 6 | +export interface EnvLoaderOptions { |
| 7 | + mode?: string; |
| 8 | + envDir?: string; |
| 9 | + prefixes?: string | string[]; |
| 10 | +} |
| 11 | + |
| 12 | +export class EnvLoader { |
| 13 | + static getEnvFilePaths(mode = "development", envDir = process.cwd()): string[] { |
| 14 | + return [ |
| 15 | + `.env`, // default file |
| 16 | + `.env.local`, // local file |
| 17 | + `.env.${mode}`, // mode file |
| 18 | + `.env.${mode}.local`, // mode local file |
| 19 | + ].map((file) => normalize(path.join(envDir, file))); |
| 20 | + } |
| 21 | + |
| 22 | + static loadEnvFiles(options: EnvLoaderOptions = {}): Record<string, string> { |
| 23 | + const { |
| 24 | + mode = process.env.NODE_ENV || "development", |
| 25 | + envDir = process.cwd(), |
| 26 | + prefixes, |
| 27 | + } = options; |
| 28 | + |
| 29 | + const normalizedPrefixes = prefixes |
| 30 | + ? Array.isArray(prefixes) |
| 31 | + ? prefixes |
| 32 | + : [prefixes] |
| 33 | + : undefined; |
| 34 | + |
| 35 | + if (mode === "local") { |
| 36 | + throw new Error( |
| 37 | + '"local" cannot be used as a mode name because it conflicts with the .local postfix for .env files.', |
| 38 | + ); |
| 39 | + } |
| 40 | + |
| 41 | + const envFiles = this.getEnvFilePaths(mode, envDir); |
| 42 | + const env: Record<string, string> = {}; |
| 43 | + |
| 44 | + // Load all env files |
| 45 | + envFiles.forEach((filePath) => { |
| 46 | + try { |
| 47 | + loadEnvFile(filePath); |
| 48 | + } catch { |
| 49 | + // Skip if file doesn't exist |
| 50 | + } |
| 51 | + }); |
| 52 | + |
| 53 | + // If prefixes are specified, filter environment variables |
| 54 | + if (normalizedPrefixes?.length) { |
| 55 | + for (const [key, value] of Object.entries(process.env)) { |
| 56 | + if (normalizedPrefixes.some((prefix) => key.startsWith(prefix))) { |
| 57 | + env[key] = value as string; |
| 58 | + } |
| 59 | + } |
| 60 | + return env; |
| 61 | + } |
| 62 | + |
| 63 | + // Return all environment variables if no prefixes specified |
| 64 | + return { ...process.env } as Record<string, string>; |
| 65 | + } |
| 66 | +} |
0 commit comments