Compare commits

...

2 Commits

Author SHA1 Message Date
autofix-ci[bot]
7a68358791 [autofix.ci] apply automated fixes 2025-09-14 07:00:12 +00:00
Claude Bot
cc6e266c53 fix(bundler): replace import.meta with undefined in CJS bundles
When bundling to CommonJS format, import.meta expressions would remain
in the bundled output, causing "TypeError: Expected CommonJS module to
have a function wrapper" errors at runtime. This fix replaces import.meta
property access with undefined when bundling to CJS format.

Fixes #22642

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-14 06:56:58 +00:00
2 changed files with 57 additions and 0 deletions

View File

@@ -876,6 +876,13 @@ pub fn VisitExpr(
.property_access_for_method_call_maybe_should_replace_with_undefined = in.property_access_for_method_call_maybe_should_replace_with_undefined,
});
// When bundling to CJS, replace import.meta.* with undefined
if (p.options.bundle and p.options.output_format == .cjs and
e_.target.data == .e_import_meta)
{
return p.newExpr(E.Undefined{}, expr.loc);
}
// 'require.resolve' -> .e_require_resolve_call_target
if (e_.target.data == .e_require_call_target and
strings.eqlComptime(e_.name, "resolve"))

View File

@@ -0,0 +1,50 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe, tempDir } from "harness";
test("import.meta should not appear in CJS bundles (issue #22642)", async () => {
using dir = tempDir("issue-22642", {
"src/index.ts": `
// This code will cause import.meta to appear in the bundle
// when bundling @sentry/bun or similar packages
const needsEsmLoader = typeof module !== "undefined" && module.register;
if (needsEsmLoader) {
module.register("some-loader", import.meta.url);
}
console.log("test");
`,
});
// Bundle to CJS format
await using proc = Bun.spawn({
cmd: [bunExe(), "build", "./src/index.ts", "--outdir", "dist", "--format", "cjs", "--target", "bun"],
env: bunEnv,
cwd: String(dir),
stderr: "pipe",
stdout: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(exitCode).toBe(0);
expect(stderr).toBe("");
// Now try to run the bundled file
await using runProc = Bun.spawn({
cmd: [bunExe(), "./dist/index.js"],
env: bunEnv,
cwd: String(dir),
stderr: "pipe",
stdout: "pipe",
});
const [runStdout, runStderr, runExitCode] = await Promise.all([
runProc.stdout.text(),
runProc.stderr.text(),
runProc.exited,
]);
// The bundled CJS file should run without errors
expect(runExitCode).toBe(0);
expect(runStderr).not.toContain("TypeError: Expected CommonJS module to have a function wrapper");
expect(runStdout).toContain("test");
});