Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/webpack-named-chunks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@opennextjs/cloudflare": patch
---

fix: inline named webpack chunks (`webpackChunkName`) in the server runtime

Apps built with webpack returned a 500 with `Error: Unknown chunk N` when the server code loaded a chunk named with `/* webpackChunkName: "..." */`, i.e. from a `next/dynamic` or `import()` in the app or in a dependency. Named chunks are now bundled into the Worker and load correctly.
1 change: 1 addition & 0 deletions examples/playground16/app/api/named-chunk/message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const message = "Loaded from a named webpack chunk";
8 changes: 8 additions & 0 deletions examples/playground16/app/api/named-chunk/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const dynamic = "force-dynamic";

// `webpackChunkName` makes webpack emit the server chunk as `chunks/named-chunk.js` instead of `chunks/<id>.js`.
// See https://github.com/opennextjs/opennextjs-cloudflare/issues/1326
export async function GET() {
const { message } = await import(/* webpackChunkName: "named-chunk" */ "./message");
return Response.json({ message });
}
9 changes: 9 additions & 0 deletions examples/playground16/e2e/named-chunk.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { expect, test } from "@playwright/test";

// Regression test for named webpack chunks (`webpackChunkName`).
// See https://github.com/opennextjs/opennextjs-cloudflare/issues/1326
test("load a named webpack chunk", async ({ request }) => {
const response = await request.get("/api/named-chunk");
expect(response.status()).toEqual(200);
expect(await response.json()).toEqual({ message: "Loaded from a named webpack chunk" });
});
218 changes: 127 additions & 91 deletions packages/cloudflare/src/cli/build/patches/ast/webpack-runtime.spec.ts
Original file line number Diff line number Diff line change
@@ -1,113 +1,149 @@
import { patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js";
import { describe, expect, test } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { buildMultipleChunksRule, singleChunkRule } from "./webpack-runtime.js";
import { applyRule, parseCode, patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js";
import { afterEach, beforeEach, describe, expect, test } from "vitest";

describe("webpack runtime", () => {
describe("multiple chunks", () => {
test("patch runtime", () => {
const code = `
/******/ // require() chunk loading for javascript
/******/ __webpack_require__.f.require = (chunkId, promises) => {
/******/ // "1" is the signal for "already loaded"
/******/ if (!installedChunks[chunkId]) {
/******/ if (658 != chunkId) {
/******/ installChunk(require("./chunks/" + __webpack_require__.u(chunkId)));
/******/
} else installedChunks[chunkId] = 1;
/******/
}
/******/
};
`;

expect(patchCode(code, buildMultipleChunksRule([1, 2, 3]))).toMatchInlineSnapshot(`
"/******/ // require() chunk loading for javascript
/******/ __webpack_require__.f.require = (chunkId, _) => {
if (!installedChunks[chunkId]) {
switch (chunkId) {
case 1: installChunk(require("./chunks/1.js")); break;
case 2: installChunk(require("./chunks/2.js")); break;
case 3: installChunk(require("./chunks/3.js")); break;
case 658: installedChunks[chunkId] = 1; break;
default: throw new Error(\`Unknown chunk \${chunkId}\`);
}
}
}
;
"
`);
});

test("patch minified runtime", () => {
const code = `
t.f.require=(o,n)=>{e[o]||(658!=o?r(require("./chunks/"+t.u(o))):e[o]=1)}
`;

expect(patchCode(code, buildMultipleChunksRule([1, 2, 3]))).toMatchInlineSnapshot(
`
"t.f.require=(o, _) => {
if (!e[o]) {
switch (o) {
case 1: r(require("./chunks/1.js")); break;
case 2: r(require("./chunks/2.js")); break;
case 3: r(require("./chunks/3.js")); break;
case 658: e[o] = 1; break;
default: throw new Error(\`Unknown chunk \${o}\`);
}
}
}

"
`
);
});
});
import { buildChunkRequireRule, listChunks } from "./webpack-runtime.js";

describe("single chunk", () => {
describe("webpack runtime", () => {
describe("buildChunkRequireRule", () => {
test("patch runtime", () => {
const code = `
/******/ // require() chunk loading for javascript
/******/ __webpack_require__.f.require = (chunkId, promises) => {
/******/ // "1" is the signal for "already loaded"
/******/ if(!installedChunks[chunkId]) {
/******/ if(710 == chunkId) {
/******/ if(658 != chunkId) {
/******/ installChunk(require("./chunks/" + __webpack_require__.u(chunkId)));
/******/ } else installedChunks[chunkId] = 1;
/******/ }
/******/ };
`;

expect(patchCode(code, singleChunkRule)).toMatchInlineSnapshot(`
"/******/ // require() chunk loading for javascript
/******/ __webpack_require__.f.require = (chunkId, _) => {
if (!installedChunks[chunkId]) {
try {
installChunk(require("./chunks/710.js"));
} catch {}
}
}
;
"
`);
expect(patchCode(code, buildChunkRequireRule(["1.js", "named-chunk.js"]))).toMatchInlineSnapshot(`
"/******/ // require() chunk loading for javascript
/******/ __webpack_require__.f.require = (chunkId, promises) => {
/******/ // "1" is the signal for "already loaded"
/******/ if(!installedChunks[chunkId]) {
/******/ if(658 != chunkId) {
/******/ installChunk(((path) => {
switch (path) {
case "./chunks/1.js": return require("./chunks/1.js");
case "./chunks/named-chunk.js": return require("./chunks/named-chunk.js");
default: throw new Error(\`Unknown chunk \${path}\`);
}
})("./chunks/" + __webpack_require__.u(chunkId))
);
/******/ } else installedChunks[chunkId] = 1;
/******/ }
/******/ };
"
`);
});

test("patch minified runtime", () => {
const code = `t.f.require=(o,n)=>{e[o]||(658!=o?r(require("./chunks/"+t.u(o))):e[o]=1)}`;

expect(patchCode(code, buildChunkRequireRule(["1.js", "named-chunk.js"]))).toMatchInlineSnapshot(`
"t.f.require=(o,n)=>{e[o]||(658!=o?r(((path) => {
switch (path) {
case "./chunks/1.js": return require("./chunks/1.js");
case "./chunks/named-chunk.js": return require("./chunks/named-chunk.js");
default: throw new Error(\`Unknown chunk \${path}\`);
}
})("./chunks/" + t.u(o))
):e[o]=1)}"
`);
});

test("patch minified runtime with a single chunk", () => {
const code = `o.f.require=(t,a)=>{e[t]||(710==t?r(require("./chunks/"+o.u(t))):e[t]=1)}`;

expect(patchCode(code, buildChunkRequireRule(["named-chunk.js"]))).toMatchInlineSnapshot(`
"o.f.require=(t,a)=>{e[t]||(710==t?r(((path) => {
switch (path) {
case "./chunks/named-chunk.js": return require("./chunks/named-chunk.js");
default: throw new Error(\`Unknown chunk \${path}\`);
}
})("./chunks/" + o.u(t))
):e[t]=1)}"
`);
});

test("escape `$` in chunk names", () => {
const code = `e.f.require=(c,d)=>{a[c]||(311!=c?b(require("./chunks/"+e.u(c))):a[c]=1)}`;

expect(patchCode(code, buildChunkRequireRule(["$CHUNK_FILE.js"]))).toContain(
`case "./chunks/\\x24CHUNK_FILE.js": return require("./chunks/\\x24CHUNK_FILE.js");`
);
});

test("run the patched runtime", () => {
const code = `
o.f.require=(t,a)=>{e[t]||(710==t?r(require("./chunks/"+o.u(t))):e[t]=1)}
`;

expect(patchCode(code, singleChunkRule)).toMatchInlineSnapshot(`
"o.f.require=(t, _) => {
if (!e[t]) {
try {
r(require("./chunks/710.js"));
} catch {}
}
}

"
`);
const installed = [];
const require = (path) => path;
const installChunk = (path) => installed.push(path);
const installedChunks = { 311: 0 };
const __webpack_require__ = { f: {} };
__webpack_require__.u = (chunkId) => "" + ({ 522: "named-chunk" }[chunkId] || chunkId) + ".js";
__webpack_require__.f.require = (chunkId, promises) => {
if (!installedChunks[chunkId]) {
if (311 != chunkId) {
installChunk(require("./chunks/" + __webpack_require__.u(chunkId)));
} else installedChunks[chunkId] = 1;
}
};
`;
const patched = patchCode(code, buildChunkRequireRule(["1.js", "named-chunk.js"]));
const run = new Function(
`${patched}
__webpack_require__.f.require(1);
__webpack_require__.f.require(522);
__webpack_require__.f.require(311);
let error;
try { __webpack_require__.f.require(404); } catch (e) { error = e.message; }
return { installed, installedChunks, error };`
);

expect(run()).toEqual({
installed: ["./chunks/1.js", "./chunks/named-chunk.js"],
installedChunks: { 311: 1 },
error: "Unknown chunk ./chunks/404.js",
});
});

test("do not match an already patched runtime", () => {
const code = `t.f.require=(o,n)=>{e[o]||(658!=o?r(require("./chunks/"+t.u(o))):e[o]=1)}`;
const patched = patchCode(code, buildChunkRequireRule(["1.js"]));

expect(applyRule(buildChunkRequireRule(["1.js"]), parseCode(patched)).edits).toHaveLength(0);
});
});

describe("listChunks", () => {
let tmpDir: string;

beforeEach(() => {
tmpDir = mkdtempSync(join(tmpdir(), "webpack-runtime-test-"));
});

afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true });
});

test("list numeric, named and nested chunks", () => {
mkdirSync(join(tmpDir, "dir"));
for (const file of ["103.js", "9.js", "named-chunk.js", "named-chunk.js.map", "dir/nested-chunk.js"]) {
writeFileSync(join(tmpDir, file), "");
}

expect(listChunks(tmpDir)).toEqual(["103.js", "9.js", "dir/nested-chunk.js", "named-chunk.js"]);
});

test("return an empty list when there is no chunks folder", () => {
expect(listChunks(join(tmpDir, "missing"))).toEqual([]);
});
});
});
Loading
Loading