Skip to content

Commit 91dbdd3

Browse files
committed
fix: detect Turbopack builds and set TURBOPACK env accordingly
When building with Turbopack (default in Next.js 16), the standalone output only includes *-turbo.runtime.prod.js files, not the webpack variants. The previous behavior of unconditionally setting TURBOPACK=false caused runtime errors because module.compiled.js would try to load non-existent runtime files. This change: - Detects Turbopack builds by checking if only turbo runtime files exist in the traced files - Sets TURBOPACK=true for Turbopack builds so the correct runtime is loaded - Keeps TURBOPACK=false for Webpack builds (existing behavior) Fixes runtime error: Cannot find module 'next/dist/compiled/next-server/pages.runtime.prod.js'
1 parent 47a84a7 commit 91dbdd3

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

packages/open-next/src/build/patch/patches/patchEnvVar.ts

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { createPatchCode } from "../astCodePatcher.js";
2-
import type { CodePatcher } from "../codePatcher";
1+
import { createPatchCode, patchCode } from "../astCodePatcher.js";
2+
import type { CodePatcher, PatchCodeFn } from "../codePatcher.js";
33

44
/**
55
* Creates a rule to replace `process.env.${envVar}` by `value` in the condition of if statements
@@ -21,6 +21,22 @@ fix:
2121
'${value}'
2222
`;
2323

24+
function isTurbopackBuild(tracedFiles: string[]): boolean {
25+
const hasTurboRuntime = tracedFiles.some((file) =>
26+
/-turbo[.-].*\.runtime\.(prod|dev)\.js$/.test(file),
27+
);
28+
const hasNonTurboRuntime = tracedFiles.some(
29+
(file) =>
30+
/\.runtime\.(prod|dev)\.js$/.test(file) && !/-turbo[.-]/.test(file),
31+
);
32+
return hasTurboRuntime && !hasNonTurboRuntime;
33+
}
34+
35+
const createTurbopackPatch: PatchCodeFn = async ({ code, tracedFiles }) => {
36+
const value = isTurbopackBuild(tracedFiles) ? "true" : "false";
37+
return patchCode(code, envVarRuleCreator("TURBOPACK", value));
38+
};
39+
2440
export const patchEnvVars: CodePatcher = {
2541
name: "patch-env-vars",
2642
patches: [
@@ -39,12 +55,12 @@ export const patchEnvVars: CodePatcher = {
3955
contentFilter: /process\.env\.NODE_ENV/,
4056
patchCode: createPatchCode(envVarRuleCreator("NODE_ENV", '"production"')),
4157
},
42-
// This patch will set `TURBOPACK` env to false to avoid loading turbopack related deps at runtime
58+
// Turbopack builds only include *-turbo.runtime.prod.js files, so we detect and set accordingly
4359
{
4460
versions: ">=15.0.0",
4561
pathFilter: /module\.compiled\.js$/,
4662
contentFilter: /process\.env\.TURBOPACK/,
47-
patchCode: createPatchCode(envVarRuleCreator("TURBOPACK", "false")),
63+
patchCode: createTurbopackPatch,
4864
},
4965
],
5066
};

0 commit comments

Comments
 (0)