Build failure: `__dirname`/`__filename` shim injection conflicts and runtime errors
#1,345 opened on 2026/05/20
Repository metrics
- Stars
- (8,563 個のスター)
- PR merge metrics
- (平均マージ 1d 1h) (30d で 462 merged PRs)
説明
This issue was created by an agent analysing CI failures from the Next.js Deploy Suite (vinext
mainvs Next.jsv16.2.6, 2026-05-20).
Problem
Two related issues with CJS compatibility shim injection:
- Redeclaration at build time. vinext injects
const __dirname = ...andconst __filename = ...CJS compatibility shims into ESM files. When the user's code already declares its ownconst __dirname = fileURLToPath(...)polyfill, Rolldown/OXC rejects the duplicateconstdeclaration in the same scope.
[PARSE_ERROR] Identifier `__dirname` has already been declared
╭─[ next.config.ts:3:7 ]
3 │ const __dirname = "/tmp/next-test-...";
- Undefined at runtime. Third-party libraries bundled into the server entry use
__dirname/__filename, but the shim injection does not cover code insidenode_modulesor 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
-
Reproduce first in vinext's own test suite. Add a test with a
next.config.tsthat declares its ownconst __dirname = ...and verify the build succeeds. Add a test with a dependency that uses__dirname. Confirm they fail. -
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. -
Ensure shims cover bundled
node_modulescode. The injection should handle code that comes from third-party packages, not just user source files. Consider using a banner/footer approach or Rolldown'sdefineoption for broader coverage.