-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
52 lines (43 loc) · 1.28 KB
/
index.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
46
47
48
49
50
51
52
'use strict';
const fs = require('fs');
const del = require('del');
const cosmiconfig = require('cosmiconfig');
const explorer = cosmiconfig('inject-env-browser-run');
module.exports = async (dest, {dotenv} = {dotenv: false}) => {
const file = `${dest}/env-config.js`;
const [, result] = await Promise.all([
del([file]),
explorer.search()
]);
if (!result || !result.config || !result.config.required) {
return console.log('No required env variables!');
}
const {config} = result;
const {required} = config;
const envSource = dotenv ? require('dotenv').config().parsed : process.env;
const mapSysEnvReducer = (obj, varName) => ({...obj, [varName]: envSource[varName]});
const envObj = required.reduce(mapSysEnvReducer, {});
const content = `window._env_ = ${JSON.stringify(envObj, null, ' ')}`;
console.log(`
========================
inject-env-browser-run
========================
`);
required.forEach(varName => {
if (envObj[varName]) {
console.log(`Success: ${varName} defined with value ${envObj[varName]}`);
} else {
console.warn(`Warn: ${varName} is undefined!`);
}
});
fs.writeFile(file, content, err => {
if (err) {
throw err;
}
console.log(`
========================
env injected to the browser successfully
========================
`);
});
};