forked from onepanelio/core-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
set-env.js
60 lines (47 loc) · 1.58 KB
/
set-env.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
53
54
55
56
57
58
59
60
const fs = require('fs');
const envVariables = {
version: process.env.VERSION,
};
const targetPath = './src/environments/';
const looseJsonParse = (obj) => {
return Function('"use strict";return (' + obj + ')')();
};
const environmentFilePath = process.env.PRODUCTION && process.env.PRODUCTION == 'true' ?
`${targetPath}environment.prod.ts` :
`${targetPath}environment.local.ts`
;
const readFile = (fileUrl) => {
return new Promise((resolve, reject) => {
fs.readFile(fileUrl, 'utf8', (error, data) => {
error ? reject(error) : resolve(data);
});
});
};
const writeFile = (fileUrl, fileData) => {
return new Promise((resolve, reject) => {
fs.writeFile(fileUrl, fileData, (error) => {
if (error) {
reject(error);
}
resolve();
})
});
};
const parseFile = (data) => {
return new Promise((resolve) => {
const regEx = new RegExp('\{([^}]+)\}', 'gm');
const matchedData = looseJsonParse(data.match(regEx)[0]);
const envObject = Object.keys(matchedData).reduce((result, objectKey) => {
return {
[objectKey]: envVariables[objectKey] || matchedData[objectKey],
...result,
};
}, {});
const fileData = `export const environment = ${JSON.stringify(envObject, null, 2)};`;
resolve(fileData);
});
};
readFile(environmentFilePath)
.then((data) => parseFile(data))
.then((fileData) => writeFile(environmentFilePath, fileData))
.catch((error) => { console.error(error); });