-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
49 lines (43 loc) · 1.63 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
const path = require("path");
const fs = require("fs");
const { findEnvFile } = require("./utils");
const DEFAULT_ENV = process.env.NODE_ENV || "development";
module.exports = {
name: "env",
setup(build) {
build.onResolve({ filter: /^env$/ }, async (args) => {
const rootPath = path.resolve('.');
const env = ((build.initialOptions?.define || {})['process.env.NODE_ENV'] || DEFAULT_ENV).replace(/"/g, '');
return {
path: args.path,
pluginData: {
...args.pluginData,
envPath: findEnvFile(args.resolveDir, rootPath, env),
},
namespace: "env-ns",
};
});
build.onLoad({ filter: /.*/, namespace: "env-ns" }, async (args) => {
let envPath = args.pluginData?.envPath;
let config = {};
let contents = '{}';
if (envPath) {
try {
// read in .env file contents and combine with regular .env:
let data = await fs.promises.readFile(envPath, "utf8");
const buf = Buffer.from(data);
config = require("dotenv").parse(buf);
contents = JSON.stringify({ ...process.env, ...config });
} catch (e) {
console.warn('Exception in esbuild-envfile-plguin build.onLoad():', e);
}
} else {
contents = JSON.stringify(process.env);
}
return {
contents,
loader: "json",
};
});
},
};