-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
53 lines (50 loc) · 1.33 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
53
const fs = require('fs');
const dotenv = require('dotenv');
const { RawSource } = require('webpack-sources');
class DotenvToExportsPlugin {
constructor (config = {}) {
this.config = {
filename: './env.js',
...config
}
}
apply (compiler) {
const pluginName = this.constructor.name;
const { env, filter, transformKey, transformValue } = this.config;
compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
const defaultsFile = dotenv.parse(fs.readFileSync('./.env'));
let envFile = {}
if (env) {
try {
envFile = dotenv.parse(fs.readFileSync(`./.env.${env}`));
} catch (e) {
console.log('No config file for env:', env);
}
}
const combinedFile = {
...defaultsFile,
...envFile
};
const activeKeys = [];
// format to exports
let exportFile = "";
for (let key in combinedFile) {
let val = combinedFile[key];
if (filter && !filter({ key, val })) {
continue;
}
if (transformKey) {
key = transformKey({ key, val });
}
if (transformValue) {
val = transformValue({ key, val });
}
activeKeys.push(key);
exportFile += `const ${key} = "${val}";\n`;
}
exportFile += `\nexport { ${activeKeys.join(', ')} }`;
compilation.emitAsset(this.config.filename, new RawSource(exportFile));
});
}
}
module.exports = DotenvToExportsPlugin;