-
Notifications
You must be signed in to change notification settings - Fork 2
/
bundle.ts
89 lines (82 loc) · 1.94 KB
/
bundle.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
89
import fs from "fs";
import path from "path";
const { runWithOptions } = require("./webpack-loader");
export type BundleInput = {
format: "iife" | "cjs" | "esm";
mode: "full" | "light" | "auto";
filepath: string;
defaultMode: "auto" | "light" | "full";
typescript: boolean;
destination: string;
directory: string;
service: boolean;
readFile: (input: string) => string;
writeFile: (path: string, content: string) => Promise<void>;
};
async function writeFile(name, content, destination, filepath) {
if (destination) {
try {
await fs.promises.writeFile(
name.replace(path.basename(filepath), path.basename(destination)),
content,
"utf8"
);
console.log("Wrote", name);
} catch (exception) {
console.error("Error writing file", name);
console.log(`// ${name}`);
console.log(content);
}
} else {
console.log(`// ${name}`);
console.log(content);
}
}
export function bundle(
source: string,
{
format,
mode,
filepath,
defaultMode = "auto",
service = false,
typescript,
destination,
readFile = fs.readFileSync,
writeFile: _writeFile,
}: BundleInput
): Promise<string> {
return new Promise((resolve, reject) => {
let activateCallbackFunction = () => {
return (err, code) => {
if (err) {
reject(err);
} else {
resolve(code);
}
};
};
const result = runWithOptions(
source,
{
mode,
typescript,
service,
},
path.resolve(filepath),
readFile,
activateCallbackFunction,
() => {},
format,
_writeFile ||
((name, content) => writeFile(name, content, destination, filepath)),
defaultMode
);
if (result === null) {
return resolve(source);
} else if (typeof result === "undefined") {
} else if (typeof result === "string") {
return resolve(result);
}
});
}