- 删除 cli.tsx 顶部的 globalThis.MACRO / BUILD_* / feature polyfill - 新增 scripts/defines.ts 作为 MACRO define 映射的单一来源 - 新增 scripts/dev.ts,通过 bun run -d 在转译时注入 MACRO 常量 - build.ts 引用 getMacroDefines() 实现构建时内联 - 清理 global.d.ts (移除 BUILD_*, MACRO 函数声明) - 55 个 MACRO 消费文件零改动 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
50 lines
1.5 KiB
TypeScript
50 lines
1.5 KiB
TypeScript
import { readdir, readFile, writeFile } from "fs/promises";
|
|
import { join } from "path";
|
|
import { getMacroDefines } from "./scripts/defines.ts";
|
|
|
|
const outdir = "dist";
|
|
|
|
// Step 1: Clean output directory
|
|
const { rmSync } = await import("fs");
|
|
rmSync(outdir, { recursive: true, force: true });
|
|
|
|
// Step 2: Bundle with splitting
|
|
const result = await Bun.build({
|
|
entrypoints: ["src/entrypoints/cli.tsx"],
|
|
outdir,
|
|
target: "bun",
|
|
splitting: true,
|
|
define: getMacroDefines(),
|
|
});
|
|
|
|
if (!result.success) {
|
|
console.error("Build failed:");
|
|
for (const log of result.logs) {
|
|
console.error(log);
|
|
}
|
|
process.exit(1);
|
|
}
|
|
|
|
// Step 3: Post-process — replace Bun-only `import.meta.require` with Node.js compatible version
|
|
const files = await readdir(outdir);
|
|
const IMPORT_META_REQUIRE = "var __require = import.meta.require;";
|
|
const COMPAT_REQUIRE = `var __require = typeof import.meta.require === "function" ? import.meta.require : (await import("module")).createRequire(import.meta.url);`;
|
|
|
|
let patched = 0;
|
|
for (const file of files) {
|
|
if (!file.endsWith(".js")) continue;
|
|
const filePath = join(outdir, file);
|
|
const content = await readFile(filePath, "utf-8");
|
|
if (content.includes(IMPORT_META_REQUIRE)) {
|
|
await writeFile(
|
|
filePath,
|
|
content.replace(IMPORT_META_REQUIRE, COMPAT_REQUIRE),
|
|
);
|
|
patched++;
|
|
}
|
|
}
|
|
|
|
console.log(
|
|
`Bundled ${result.outputs.length} files to ${outdir}/ (patched ${patched} for Node.js compat)`,
|
|
);
|