Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion test/cli/run/module-type-fixture/cjs/import.cjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import * as fs from "node:fs";
console.log(eval("typeof module === 'undefined'"));
+fs;
fs.constants;
2 changes: 1 addition & 1 deletion test/cli/run/module-type-fixture/esm/import.cjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import * as fs from "node:fs";
console.log(eval("typeof module === 'undefined'"));
+fs;
fs.constants;
61 changes: 61 additions & 0 deletions test/cli/run/run-detect-module-type.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe } from "harness";
import { join } from "path";

// package.json "type" -> file name -> expected module type of the main entry
const table = {
cjs: {
"hello.cjs": "commonjs",
"hello.js": "commonjs",
"hello.mjs": "module",
"hello.ts": "commonjs",
"hello.tsx": "module",
"hello.cts": "commonjs",
"hello.jsx": "module",
"hello.mts": "module",
// files using ES import and no exports will be detected as module
"import.cjs": "module",
},
esm: {
"hello.cjs": "commonjs",
"hello.js": "module",
"hello.mjs": "module",
"hello.ts": "module",
"hello.tsx": "module",
"hello.cts": "commonjs",
"hello.jsx": "module",
"hello.mts": "module",
// files using ES import and no exports will be detected as module
"import.cjs": "module",
},
} as const;

const cases = Object.entries(table).flatMap(([packageType, files]) =>
Object.entries(files).map(([file, expectedType]) => ({ packageType, file, expectedType })),
);

test("detect module type", async () => {
// each fixture prints `typeof module === 'undefined'`: "false" means it ran as commonjs
const actual = await Promise.all(
cases.map(async ({ packageType, file }) => {
await using proc = Bun.spawn({
cmd: [bunExe(), "run", join(import.meta.dir, "module-type-fixture", packageType, file)],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
if (exitCode !== 0) {
throw new Error(`Failed to run ${packageType}/${file}: ${stderr.trim()}`);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
const out = stdout.trim();
const detected =
out === "true" ? "module" : out === "false" ? "commonjs" : `unexpected output ${JSON.stringify(out)}`;
return `${packageType} ${file} -> ${detected}`;
}),
);

expect(actual).toEqual(
cases.map(({ packageType, file, expectedType }) => `${packageType} ${file} -> ${expectedType}`),
);
});
54 changes: 0 additions & 54 deletions test/cli/run/run-detect-module-type.ts

This file was deleted.