-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathenv.loader.js
45 lines (38 loc) · 1.17 KB
/
env.loader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const fs = require('fs');
const dotenv = require('dotenv');
const dotenvExpand = require('dotenv-expand');
const { paths } = require('./utils');
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
'`NODE_ENV` environment variable was missing. Please specify it before running.'
);
}
// using .env.[NODE_ENV] file instead when not in `production` environment
let envFile = `${paths.config}/.env`;
if (NODE_ENV !== 'production') {
envFile = `${envFile}.${NODE_ENV}`;
}
// expand existing environment variables with targeted .env file
let parsed;
if (fs.existsSync(envFile)) {
const result = dotenvExpand.expand(dotenv.config({ path: envFile }));
parsed = result.parsed;
}
function getDefinedVars() {
// return empty object instead when none was parsed
if (!parsed) {
return { parsed: {}, stringified: {} };
}
// populate key/value based on parsed env result for DefinePlugin
const stringified = Object.keys(parsed).reduce((result, key) => {
result[`process.env.${key}`] = JSON.stringify(parsed[key]);
return result;
}, {});
return { parsed, stringified };
}
// export env related
module.exports = {
envFile,
getDefinedVars
};