1 |
|
2 |
|
3 | import type {FileSystem} from '@parcel/fs';
|
4 | import type {EnvMap} from '@parcel/types';
|
5 |
|
6 | import {resolveConfig} from '@parcel/utils';
|
7 | import dotenv from 'dotenv';
|
8 | import variableExpansion from 'dotenv-expand';
|
9 |
|
10 | export 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 |
|
20 |
|
21 |
|
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 |
|
35 |
|
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 |
|
50 | return Object.assign({}, ...envs);
|
51 | }
|