MCPcopy
hub / github.com/vercel/next.js / loadEnvConfig

Function loadEnvConfig

packages/next-env/index.ts:114–180  ·  view source on GitHub ↗
(
  dir: string,
  dev?: boolean,
  log: Log = console,
  forceReload = false,
  onReload?: (envFilePath: string) => void
)

Source from the content-addressed store, hash-verified

112}
113
114export 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 }

Callers 8

loadEnvConfigMethod · 0.90
loadConfigFunction · 0.90
getEnvInfoFunction · 0.90
exportAppImplFunction · 0.90
codegen.tsFile · 0.90
startWatcherFunction · 0.50
knexfile.jsFile · 0.50

Calls 9

replaceProcessEnvFunction · 0.85
assignMethod · 0.80
isFileMethod · 0.80
readFileSyncMethod · 0.80
processEnvFunction · 0.70
pushMethod · 0.65
errorMethod · 0.65
filterMethod · 0.45
joinMethod · 0.45

Tested by

no test coverage detected