-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (53 loc) · 1.55 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
54
55
56
57
58
59
const fs = require("fs");
const { loadEnv } = require("vite");
module.exports = function vitePluginEnvDTS(option = {}) {
const path = option.path || "types/vite-env.d.ts";
const prefix = option.prefix;
const parser = option.parser || "auto";
const arrayType = option.arrayType || "array";
return {
name: "vite-plugin-env-dts",
config(_, { mode }) {
let env = loadEnv(mode, process.cwd(), prefix);
if (!env || Object.keys(env).length === 0) return;
env = parse(env, parser, arrayType);
const template = JSON.stringify(env, null, 2)
.replace(/"/g, "")
.replace(/,/g, ";")
.replace(/([\n\r])}$/, ";$1}");
const str = `interface ImportMetaEnv ${template}`;
fs.writeFile(path, str, { encoding: "utf-8" }, console.error);
},
};
};
const toString = Object.prototype.toString;
function getType(x) {
return mapper[toString.call(x)] || "undefined";
}
function parse(env, parser, arrayType) {
for (const key in env) {
const value = env[key];
if (typeof parser === "function") {
env = parser(key, value);
} else {
if (arrayType === "array" && getType(value) === "array") {
// 去重
const a = Array.from(new Set(parse(value)));
env[key] = `Array<${a.join("|")}>`;
} else if (typeof value === "object") {
parse(value);
} else if (parser === "auto") {
env[key] = getType(value);
}
}
}
return env;
}
const mapper = {
"[object String]": "string",
"[object Number]": "number",
"[object Boolean]": "boolean",
"[object Null]": "null",
"[object Array]": "array",
"[object Object]": "Record<string,any>",
};