-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathbuild.mjs
More file actions
104 lines (92 loc) · 2.82 KB
/
build.mjs
File metadata and controls
104 lines (92 loc) · 2.82 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import path from 'path';
import glob from 'fast-glob';
import { fileURLToPath } from 'url';
import ts from "typescript";
import esbuild from "esbuild";
// we need to change up how __dirname is used for ES6 purposes
const __dirname = path.dirname(fileURLToPath(import.meta.url));
async function main() {
// Absolute path to package directory
const basePath = __dirname;
const target = "es2017";
// Get all .ts as input files
const entryPoints = glob.sync(path.resolve(basePath, "src", "**", "**.ts")
.replace(/\\/g, '/')); // windows support
const outdir = path.join(basePath, 'build');
// Emit only .d.ts files
const emitTSDeclaration = () => {
console.log("Generating .d.ts...");
const program = ts.createProgram(entryPoints, {
declaration: true,
emitDeclarationOnly: true,
skipLibCheck: true,
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2017,
outDir: outdir,
esModuleInterop: true,
experimentalDecorators: true,
});
const emitResult = program.emit();
const allDiagnostics = ts
.getPreEmitDiagnostics(program)
.concat(emitResult.diagnostics);
allDiagnostics.forEach(diagnostic => {
if (diagnostic.file) {
const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
} else {
console.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
}
});
}
// CommonJS output
console.log("Generating CJS build...");
esbuild.build({
entryPoints,
outdir,
target,
format: "cjs",
target: "es2017",
sourcemap: "external",
platform: "node",
outExtension: { '.js': '.cjs', },
plugins: [{
name: 'add-cjs',
setup(build) {
build.onResolve({ filter: /.*/ }, (args) => {
if (args.importer) {
if (args.path.startsWith('.')) {
return { path: args.path.replace(/\.[jt]sx?$/, '.cjs'), external: true }
}
return { path: args.path, external: true }
}
})
},
}],
});
// ESM output
console.log("Generating ESM build...");
esbuild.build({
entryPoints,
outdir,
target,
format: "esm",
bundle: true,
sourcemap: "external",
platform: "node",
outExtension: { '.js': '.mjs', },
plugins: [{
name: 'add-mjs',
setup(build) {
build.onResolve({ filter: /.*/ }, (args) => {
if (args.importer) return { path: args.path.replace(/^\.(.*)\.js$/, '.$1.mjs'), external: true }
})
},
}]
});
// emit .d.ts files
emitTSDeclaration();
console.log("Done!");
}
export default await main();