-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathbuild.ts
66 lines (60 loc) · 1.79 KB
/
build.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
import esbuild from 'esbuild';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
const dirname = path.dirname(fileURLToPath(import.meta.url));
build(path.join(dirname, '../node_modules/assert'), path.join(dirname, '../shim/assert.mjs'));
/** build */
function build(input: string, out: string, injects: string[] = []) {
// eslint-disable-next-line no-console -- ignore
console.log(`build@ ${input}`);
let code = bundle(input, ['path', ...injects]);
code = transform(code, ['path', ...injects]);
fs.writeFileSync(out, code, 'utf8');
}
/** bundle */
function bundle(entryPoint: string, externals: string[]) {
const result = esbuild.buildSync({
entryPoints: [entryPoint],
format: 'esm',
bundle: true,
external: externals,
write: false,
inject: [path.join(dirname, './src/process-shim.mjs')]
});
return `${result.outputFiles[0].text}`;
}
/** transform code */
function transform(code: string, injects: string[]) {
const newCode = code.replace(/"[a-z]+" = "[a-z]+";/, '');
// const newCode = babelCore.transformSync(code, {
// babelrc: false,
// plugins: [
// {
// visitor: {
// CallExpression(path) {
// const callee = path.get("callee")
// if (
// callee.type === "Identifier" &&
// callee.node.name === "__require"
// ) {
// callee.replaceWith(t.identifier("__$$$require"))
// }
// },
// },
// },
// ],
// })
return `
${injects
.map((inject) => `import $inject_${inject.replace(/-/g, '_')}$ from '${inject}';`)
.join('\n')}
const $_injects_$ = {${injects
.map((inject) => `${inject.replace(/-/g, '_')}:$inject_${inject}$`)
.join(',\n')}};
function require(module, ...args) {
return $_injects_$[module] || {}
}
${newCode}
`;
}