-
Notifications
You must be signed in to change notification settings - Fork 816
/
utils.ts
54 lines (46 loc) · 1.44 KB
/
utils.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
import { build, OutputFile } from "esbuild";
import { readFileSync } from "fs";
import { join } from "path";
// e.g:
// flat/node_modules/electron/index.js?v=19cea64f => flat/node_modules/electron/index.js
const removeQueryString = (url: string): string => url.replace(/\?.*$/s, "").replace(/#.*$/s, "");
const bundleModel = (filePath: string): Promise<OutputFile[]> => {
return build({
entryPoints: [filePath],
bundle: true,
outfile: "index.js",
platform: "node",
write: false,
})
.then(({ outputFiles }) => outputFiles)
.catch(error => {
console.error(error);
return [];
});
};
export const cjs2esm = async (
id: string,
entries: Array<{ entryPoints: string; code: string; shouldBundle: boolean }>,
): Promise<string | null> => {
const filePath = removeQueryString(id);
for (const { entryPoints, code, shouldBundle } of entries) {
if (!filePath.endsWith(entryPoints)) {
continue;
}
if (!shouldBundle) {
return code;
}
const outputFiles = await bundleModel(filePath);
if (outputFiles.length === 0) {
return code;
}
return outputFiles
.map(({ text }) => text)
.join("")
.concat(code);
}
return null;
};
export function getTemplate(path: string): string {
return readFileSync(join(__dirname, path), "utf8");
}