-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathesbuild.mjs
89 lines (79 loc) · 2.55 KB
/
esbuild.mjs
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 { readFileSync } from 'node:fs';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as esbuild from 'esbuild';
const __dirname = dirname(fileURLToPath(import.meta.url));
const packagePath = process.cwd();
const files = process.argv.slice(2);
if (files.length === 0) {
throw new Error('must pass filename of entrypoints');
}
const [tsconfig, packageJson] = [
readFileSync(`${__dirname}/tsconfig.json`, 'utf8'),
readFileSync(`${packagePath}/package.json`, 'utf8'),
].map(JSON.parse);
const external = {
'@jridgewell/gen-mapping': 'genMapping',
'@ampproject/remapping': 'remapping',
'@jridgewell/source-map': 'sourceMap',
'@jridgewell/sourcemap-codec': 'sourcemapCodec',
'@jridgewell/trace-mapping': 'traceMapping',
'@jridgewell/resolve-uri': 'resolveURI',
};
/** @type {esbuild.Plugin} */
const externalize = {
name: 'externalize',
setup(build) {
build.onResolve({ filter: /^[^./]/ }, ({ path }) => {
if (!external[path]) {
throw new Error(`unregistered external module "${path}"`);
}
return { path, external: true };
});
},
};
/** @type {esbuild.Plugin} */
const umd = {
name: 'umd',
setup(build) {
const dependencies = Object.keys(packageJson.dependencies || {}).map((d) => {
return `"${d}": global.${external[d]}`;
});
build.initialOptions.banner = {
js: `
(function (global, factory, e, m) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require, exports, module) :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(function(spec) {
return {${dependencies.join(', ')}}[spec];
}, e = {}, m = { exports: e }), global.${external[packageJson.name]} = m.exports);
})(this, (function (require, exports, module) {
`.trim(),
};
build.initialOptions.footer = {
js: '}));',
};
},
};
async function build(esm) {
const build = await esbuild.build({
entryPoints: files.map((f) => `src/${f}`),
outdir: 'dist',
bundle: true,
sourcemap: 'linked',
sourcesContent: false,
format: esm ? 'esm' : 'cjs',
plugins: esm ? [externalize] : [externalize, umd],
outExtension: esm ? { '.js': '.mjs' } : { '.js': '.umd.js' },
target: tsconfig.compilerOptions.target,
});
if (build.errors.length > 0) {
for (const message of build.errors) {
console.error(message);
}
process.exit(1);
}
console.log(`Compiled ${esm ? 'esm' : 'cjs'}`);
}
build(true);
build(false);