build.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { readdir, readFile, writeFile } from "fs/promises";
  2. import { join } from "path";
  3. import { getMacroDefines } from "./scripts/defines.ts";
  4. const outdir = "dist";
  5. // Step 1: Clean output directory
  6. const { rmSync } = await import("fs");
  7. rmSync(outdir, { recursive: true, force: true });
  8. // Step 2: Bundle with splitting
  9. const result = await Bun.build({
  10. entrypoints: ["src/entrypoints/cli.tsx"],
  11. outdir,
  12. target: "bun",
  13. splitting: true,
  14. define: getMacroDefines(),
  15. });
  16. if (!result.success) {
  17. console.error("Build failed:");
  18. for (const log of result.logs) {
  19. console.error(log);
  20. }
  21. process.exit(1);
  22. }
  23. // Step 3: Post-process — replace Bun-only `import.meta.require` with Node.js compatible version
  24. const files = await readdir(outdir);
  25. const IMPORT_META_REQUIRE = "var __require = import.meta.require;";
  26. const COMPAT_REQUIRE = `var __require = typeof import.meta.require === "function" ? import.meta.require : (await import("module")).createRequire(import.meta.url);`;
  27. let patched = 0;
  28. for (const file of files) {
  29. if (!file.endsWith(".js")) continue;
  30. const filePath = join(outdir, file);
  31. const content = await readFile(filePath, "utf-8");
  32. if (content.includes(IMPORT_META_REQUIRE)) {
  33. await writeFile(
  34. filePath,
  35. content.replace(IMPORT_META_REQUIRE, COMPAT_REQUIRE),
  36. );
  37. patched++;
  38. }
  39. }
  40. console.log(
  41. `Bundled ${result.outputs.length} files to ${outdir}/ (patched ${patched} for Node.js compat)`,
  42. );