generated from rhdeck/ts-template
/
make-index.ts
88 lines (87 loc) · 2.63 KB
/
make-index.ts
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env ts-node
import { readdirSync, writeFileSync, lstatSync } from "fs";
import { join, basename } from "path";
import { format } from "prettier";
const base = ".";
export function getExports(
base: string = ".",
context = join(process.cwd(), "src")
): [string[], string[]][] {
const files = readdirSync(join(__dirname, base));
return files
.filter(
(file: string) =>
base !== "." || !["index.ts", basename(__filename)].includes(file)
)
.map<[string[], string[]]>((file: string) => {
if (lstatSync(join(__dirname, base, file)).isDirectory()) {
return getExports(join(base, file), context).reduce(
([is, es], [i, e]) => [
[...is, ...i],
[...es, ...e],
],
<[string[], string[]]>[[], []]
);
}
const moduleName = basename(file).replace(/\.[^/.]+$/, "");
const path = join(__dirname, base, file);
if (!lstatSync(path).isFile()) return [[], []];
try {
const out = require(path);
const keys = Object.keys(out);
if (!keys.length) return [['import "./' + moduleName + '";'], []];
let i = "import ";
let e: string[] = [];
if (keys.includes("default")) {
i = i + moduleName + " ";
e.push(moduleName);
}
const namedExports = keys.filter((key) => key !== "default");
if (namedExports.length) {
if (keys.includes("default")) i = i + ",";
i =
i +
" {" +
namedExports
.map((x) => x + " as " + moduleName + "_" + x)
.join(",") +
"}";
e.push(
...namedExports.map((x) => {
return moduleName + "_" + x;
})
);
}
i = i + " from " + '"./' + moduleName + '";';
return <[string[], string[]]>[[i], e];
} catch (e) {
console.error("That was not good at all at path", path);
console.error((e as Error).message);
console.error(JSON.stringify(e));
process.exit(1);
}
})
.filter(Boolean);
}
export function makeIndex(
exports: [string[], string[]][],
indexPath = "./src/index.ts"
) {
const arr = exports.reduce(
([is, es], [i, e]) => [
[...is, ...i],
[...es, ...e],
],
<[string[], string[]]>[[], []]
);
const out =
"/** THIS FILE IS AUTO_GENERATED - MODIFICATIONS MAY NOT BE SAVED */\n" +
arr[0].join("\n") +
"\n export{" +
arr[1].join(",") +
"};";
writeFileSync(indexPath, format(out, { parser: "typescript" }));
}
const [, , out] = process.argv;
const x = getExports(".");
makeIndex(x, out);