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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ tests/e2e/cloudflare-workers/fixtures/client-module-with-package-type/node_modul
tests/fixtures/cf-app-basic/node_modules/*
!tests/fixtures/cf-app-basic/node_modules/module-identity-dependency/
!tests/fixtures/cf-app-basic/node_modules/module-identity-dependency/**
!tests/fixtures/cf-app-basic/node_modules/pages-only-dependency/
!tests/fixtures/cf-app-basic/node_modules/pages-only-dependency/**
dist/
!packages/types/next/upstream/dist/
!packages/types/next/upstream/dist/**
Expand Down
16 changes: 11 additions & 5 deletions packages/vinext/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4245,6 +4245,12 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] {
instrumentationClientPath,
].flatMap((entry) => (entry ? [toRelativeFileEntry(root, entry)] : []));
const optimizeEntries = [...new Set([...appEntries, ...explicitInstrumentationEntries])];
// Pages Router modules render in ssr and hydrate in client, never in
// rsc. Without these, each dependency only pages/ imports is found on
// the first request for its page, re-optimizing and reloading.
const ssrAndClientOptimizeEntries = hasPagesDir
? [...optimizeEntries, toRelativeFileEntry(root, pagesDir) + "/**/*.{tsx,ts,jsx,js}"]
: optimizeEntries;
const additionalRscOptimizeIncludes: string[] = [];
if (
env.command === "serve" &&
Expand Down Expand Up @@ -4473,7 +4479,7 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] {
...(userSsrExternal === true || externalizeSsrReactInDev || hasCloudflarePlugin
? {}
: { include: ["react-dom/server", "react-dom/static"] }),
entries: optimizeEntries,
entries: ssrAndClientOptimizeEntries,
...depOptimizeNodeEnvOptions,
},
build: {
Expand Down Expand Up @@ -4505,10 +4511,10 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] {
shimOptimizeDepsExclude,
nextServerExternal,
),
// Crawl app/ source files up front so client-only deps imported
// by user components are discovered during startup instead of
// triggering a late re-optimisation + full page reload.
entries: optimizeEntries,
// Crawl app/ and pages/ source files up front so client-only
// deps imported by user components are discovered during startup
// instead of triggering a late re-optimisation + full page reload.
entries: ssrAndClientOptimizeEntries,
// React packages aren't crawled from app/ source files,
// so must be pre-included to avoid late discovery (#25).
include: [
Expand Down
4 changes: 4 additions & 0 deletions tests/app-router-dev-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2322,6 +2322,10 @@ describe("App Router integration", () => {
expect(ssrGlob).toContain("instrumentation-client.ts");
expect(clientGlob).toContain("instrumentation.ts");
expect(clientGlob).toContain("instrumentation-client.ts");
// Pages Router modules render in ssr and hydrate in client, never in rsc.
expect(ssrEntries).toContain("pages/**/*.{tsx,ts,jsx,js}");
expect(clientEntries).toContain("pages/**/*.{tsx,ts,jsx,js}");
expect(rscEntries).not.toContain("pages/**/*.{tsx,ts,jsx,js}");
});

it("pre-includes framework dependencies in optimizeDeps.include to avoid late discovery", () => {
Expand Down
55 changes: 53 additions & 2 deletions tests/dep-scan-bundled-deps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, it } from "vite-plus/test";
import { createIsolatedFixture } from "./helpers.js";

// vinext inlines some dependencies (for example ua-parser-js behind the
// next/server userAgent shim) into dist/deps, already converted to ESM. Source
Expand Down Expand Up @@ -150,9 +151,9 @@ const LINKED_CLIENT_SHIM_SPECIFIERS = [
"next/web-vitals",
];

function runProbe<T = { errors: string[] }>(root: string): Promise<T> {
function runProbe<T = { errors: string[] }>(root: string, args = ["probe.mjs"]): Promise<T> {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, ["probe.mjs"], {
const child = spawn(process.execPath, args, {
cwd: root,
stdio: ["ignore", "pipe", "pipe"],
});
Expand Down Expand Up @@ -322,6 +323,34 @@ try {
return root;
}

// Reports the dependencies the Cloudflare hybrid fixture's client and ssr
// optimizers, where Pages Router modules load, find at startup. Cloudflare's
// Worker environments discover dependencies; Node dev's do not.
const CF_APP_BASIC_DIR = path.resolve(import.meta.dirname, "fixtures/cf-app-basic");
function startupDepsProbe(root: string): string {
return `import { createLogger, createServer } from "vite";
const server = await createServer({
root: ${JSON.stringify(root)},
configFile: ${JSON.stringify(path.join(root, "vite.config.ts"))},
cacheDir: ${JSON.stringify(path.join(root, ".vite"))},
customLogger: createLogger("silent"),
server: { host: "127.0.0.1", port: 0 },
});
try {
await server.listen();
const deps = {};
for (const name of ["client", "ssr"]) {
const optimizer = server.environments[name].depsOptimizer;
await optimizer.scanProcessing;
deps[name] = [...Object.keys(optimizer.metadata.optimized), ...Object.keys(optimizer.metadata.discovered)];
}
console.log("probe:" + JSON.stringify(deps));
} finally {
await server.close();
}
`;
}

afterEach(() => {
for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
});
Expand Down Expand Up @@ -377,3 +406,25 @@ describe("client dependency scan", () => {
expect(navigationUrls.runtime).toBe(navigationUrls.app);
}, 60_000);
});

describe("hybrid dependency scan", () => {
// With both routers, a dependency only pages/ imports would otherwise be
// found on the first request for its page, re-optimizing and reloading.
it("discovers dependencies only Pages Router pages import at startup", async () => {
// Wrangler writes local state into the project, which other tests copy.
const root = await createIsolatedFixture(
CF_APP_BASIC_DIR,
"vinext-hybrid-dep-scan-",
undefined,
path.join(CF_APP_BASIC_DIR, "node_modules"),
);
roots.push(root);
const deps = await runProbe<Record<"client" | "ssr", string[]>>(root, [
"--input-type=module",
"--eval",
startupDepsProbe(root),
]);
expect(deps.client).toContain("pages-only-dependency");
expect(deps.ssr).toContain("pages-only-dependency");
}, 60_000);
});

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions tests/fixtures/cf-app-basic/pages/pages-only-dependency.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Nothing under app/ imports pages-only-dependency, so the dev optimizers only
// find it by scanning pages/ at startup.
import { pagesOnlyMessage } from "pages-only-dependency";

export default function PagesOnlyDependencyPage() {
return <p data-testid="pages-only-dependency">{pagesOnlyMessage}</p>;
}
Loading