( dir: string, dev?: boolean, log: Log = console, forceReload = false, onReload?: (envFilePath: string) => void )
| 112 | } |
| 113 | |
| 114 | export function loadEnvConfig( |
| 115 | dir: string, |
| 116 | dev?: boolean, |
| 117 | log: Log = console, |
| 118 | forceReload = false, |
| 119 | onReload?: (envFilePath: string) => void |
| 120 | ): { |
| 121 | combinedEnv: Env |
| 122 | parsedEnv: Env | undefined |
| 123 | loadedEnvFiles: LoadedEnvFiles |
| 124 | } { |
| 125 | if (!initialEnv) { |
| 126 | initialEnv = Object.assign({}, process.env) |
| 127 | } |
| 128 | // only reload env when forceReload is specified |
| 129 | if (combinedEnv && !forceReload) { |
| 130 | return { combinedEnv, parsedEnv, loadedEnvFiles: cachedLoadedEnvFiles } |
| 131 | } |
| 132 | replaceProcessEnv(initialEnv) |
| 133 | previousLoadedEnvFiles = cachedLoadedEnvFiles |
| 134 | cachedLoadedEnvFiles = [] |
| 135 | |
| 136 | const isTest = process.env.NODE_ENV === 'test' |
| 137 | const mode = isTest ? 'test' : dev ? 'development' : 'production' |
| 138 | const dotenvFiles = [ |
| 139 | `.env.${mode}.local`, |
| 140 | // Don't include `.env.local` for `test` environment |
| 141 | // since normally you expect tests to produce the same |
| 142 | // results for everyone |
| 143 | mode !== 'test' && `.env.local`, |
| 144 | `.env.${mode}`, |
| 145 | '.env', |
| 146 | ].filter(Boolean) as string[] |
| 147 | |
| 148 | for (const envFile of dotenvFiles) { |
| 149 | // only load .env if the user provided has an env config file |
| 150 | const dotEnvPath = path.join(dir, envFile) |
| 151 | |
| 152 | try { |
| 153 | const stats = fs.statSync(dotEnvPath) |
| 154 | |
| 155 | // make sure to only attempt to read files or named pipes |
| 156 | if (!stats.isFile() && !stats.isFIFO()) { |
| 157 | continue |
| 158 | } |
| 159 | |
| 160 | const contents = fs.readFileSync(dotEnvPath, 'utf8') |
| 161 | cachedLoadedEnvFiles.push({ |
| 162 | path: envFile, |
| 163 | contents, |
| 164 | env: {}, // This will be populated in processEnv |
| 165 | }) |
| 166 | } catch (err: any) { |
| 167 | if (err.code !== 'ENOENT') { |
| 168 | log.error(`Failed to load env from ${envFile}`, err) |
| 169 | } |
| 170 | } |
| 171 | } |
no test coverage detected