|
| 1 | +import { build } from "esbuild"; |
| 2 | +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; |
| 3 | +import { tmpdir } from "node:os"; |
| 4 | +import { join } from "node:path"; |
| 5 | +import { createRequire } from "node:module"; |
| 6 | +import { fileURLToPath } from "node:url"; |
| 7 | +import { spawnSync } from "node:child_process"; |
| 8 | +import { afterAll, expect, test } from "vitest"; |
| 9 | + |
| 10 | +const packageDir = fileURLToPath(new URL("../", import.meta.url)); |
| 11 | +const tempDir = mkdtempSync(join(tmpdir(), "redis-worker-build-output-")); |
| 12 | + |
| 13 | +const require = createRequire(import.meta.url); |
| 14 | + |
| 15 | +afterAll(() => { |
| 16 | + rmSync(tempDir, { recursive: true, force: true }); |
| 17 | +}); |
| 18 | + |
| 19 | +test("the ESM output can be rebundled and loaded as CommonJS", async () => { |
| 20 | + const buildResult = spawnSync("pnpm", ["exec", "tsdown"], { |
| 21 | + cwd: packageDir, |
| 22 | + encoding: "utf8", |
| 23 | + }); |
| 24 | + const buildOutput = [buildResult.stdout, buildResult.stderr].filter(Boolean).join("\n"); |
| 25 | + |
| 26 | + expect(buildResult.error, buildOutput).toBeUndefined(); |
| 27 | + expect(buildResult.status, buildOutput).toBe(0); |
| 28 | + |
| 29 | + const esmPath = join(packageDir, "dist/index.js"); |
| 30 | + const esmOutput = readFileSync(esmPath, "utf8"); |
| 31 | + expect(esmOutput).not.toMatch(/\b[\w$]*createRequire[\w$]*\s*\(\s*import\.meta\.url\s*\)/); |
| 32 | + |
| 33 | + const cjsPath = join(tempDir, "index.cjs"); |
| 34 | + await build({ |
| 35 | + entryPoints: [esmPath], |
| 36 | + outfile: cjsPath, |
| 37 | + bundle: true, |
| 38 | + format: "cjs", |
| 39 | + platform: "node", |
| 40 | + logLevel: "silent", |
| 41 | + }); |
| 42 | + |
| 43 | + expect(() => require(cjsPath)).not.toThrow(); |
| 44 | +}, 30_000); |
0 commit comments