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.

貢獻者指南