cloudflare/vinext

Build failure: `__dirname`/`__filename` shim injection conflicts and runtime errors

已关闭

#1,345 创建于 2026年5月20日

 (1 条评论) (0 个反应) (0 位负责人)TypeScript (383 个派生)github user discovery
adapter-api-e2ehelp wanted

仓库指标

星标
 (8,624 个星标)
PR 合并指标
 (平均合并 1天 1小时) (30 天内合并 462 个 PR)

描述

This issue was created by an agent analysing CI failures from the Next.js Deploy Suite (vinext main vs Next.js v16.2.6, 2026-05-20).

Problem

Two related issues with CJS compatibility shim injection:

  1. Redeclaration at build time. vinext injects const __dirname = ... and const __filename = ... CJS compatibility shims into ESM files. When the user's code already declares its own const __dirname = fileURLToPath(...) polyfill, Rolldown/OXC rejects the duplicate const declaration in the same scope.
[PARSE_ERROR] Identifier `__dirname` has already been declared
   ╭─[ next.config.ts:3:7 ]
 3 │ const __dirname = "/tmp/next-test-...";
  1. Undefined at runtime. Third-party libraries bundled into the server entry use __dirname/__filename, but the shim injection does not cover code inside node_modules or dynamically evaluated code. The production build emits ESM ("type": "module"), so CJS globals are unavailable.
ReferenceError: __dirname is not defined in ES module scope
    at file:///tmp/.../dist/server/entry.js:14560:78

Estimated Impact

~5 test failures across the deploy suite (2 build-time, 3 runtime).

Affected Test Suites

  • test/e2e/app-dir/next-config-ts/*.test.ts (2 build failures)
  • test/e2e/prerender-native-module.test.ts (1 runtime failure)
  • test/e2e/app-dir/turbopack-reports/turbopack-reports.test.ts (1 runtime failure)

Recommendation

  1. Reproduce first in vinext's own test suite. Add a test with a next.config.ts that declares its own const __dirname = ... and verify the build succeeds. Add a test with a dependency that uses __dirname. Confirm they fail.

  2. Detect existing declarations before injection. Before injecting const __dirname = ..., scan the module scope for existing declarations of the same identifier and skip injection if one exists.

  3. Ensure shims cover bundled node_modules code. The injection should handle code that comes from third-party packages, not just user source files. Consider using a banner/footer approach or Rolldown's define option for broader coverage.

贡献者指南