UNPKG

1.41 kBJavaScriptView Raw
1// @flow strict-local
2
3import type {FileSystem} from '@parcel/fs';
4import type {EnvMap} from '@parcel/types';
5
6import {resolveConfig} from '@parcel/utils';
7import dotenv from 'dotenv';
8import variableExpansion from 'dotenv-expand';
9
10export default async function loadEnv(
11 env: EnvMap,
12 fs: FileSystem,
13 filePath: string,
14): Promise<EnvMap> {
15 const NODE_ENV = env.NODE_ENV ?? 'development';
16
17 const dotenvFiles = [
18 '.env',
19 // Don't include `.env.local` for `test` environment
20 // since normally you expect tests to produce the same
21 // results for everyone
22 NODE_ENV === 'test' ? null : '.env.local',
23 `.env.${NODE_ENV}`,
24 `.env.${NODE_ENV}.local`,
25 ].filter(Boolean);
26
27 let envs = await Promise.all(
28 dotenvFiles.map(async dotenvFile => {
29 const envPath = await resolveConfig(fs, filePath, [dotenvFile]);
30 if (envPath == null) {
31 return;
32 }
33
34 // `ignoreProcessEnv` prevents dotenv-expand from writing values into `process.env`:
35 // https://github.com/motdotla/dotenv-expand/blob/ddb73d02322fe8522b4e05b73e1c1ad24ea7c14a/lib/main.js#L5
36 let output = variableExpansion({
37 parsed: dotenv.parse(await fs.readFile(envPath)),
38 ignoreProcessEnv: true,
39 });
40
41 if (output.error != null) {
42 throw output.error;
43 }
44
45 return output.parsed;
46 }),
47 );
48
49 // $FlowFixMe
50 return Object.assign({}, ...envs);
51}