Unverified Commit e10694b2 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Turbopack: preload _app's next/dynamic chunks with _app's availability in dev

Since #98823 chains the /_app and page client module graphs in development, a page's react-loadable manifest also contains the next/dynamic imports of /_app, chunked with the page's availability. Those don't match the chunks /_app's own async loader requests, so the preloaded chunks 404. Chunk /_app's imports with /_app's own module graph and availability, and the page's own imports as before.
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent c632caf3
......@@ -29,10 +29,13 @@ use next_core::{
segment_config::ParseSegmentMode,
util::{NextRuntime, get_asset_prefix_from_pathname, pages_function_name},
};
use rustc_hash::FxHashSet;
use smallvec::smallvec;
use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Completion, FxIndexMap, ResolvedVc, ValueToString, Vc, fxindexmap, fxindexset};
use turbo_tasks::{
Completion, FxIndexMap, ReadRef, ResolvedVc, ValueToString, Vc, fxindexmap, fxindexset,
};
use turbo_tasks_fs::{
self, File, FileContent, FileSystem, FileSystemPath, FileSystemPathOption, VirtualFileSystem,
};
......@@ -72,7 +75,9 @@ use crate::{
},
font::FontManifest,
loadable_manifest::create_react_loadable_manifest,
module_graph::{NextDynamicGraphs, validate_pages_css_imports},
module_graph::{
DynamicImportEntriesWithImporter, NextDynamicGraphs, validate_pages_css_imports,
},
nft::{EndpointTraceResult, trace_endpoint},
nft_json::NftJsonAsset,
paths::{
......@@ -653,6 +658,72 @@ async fn client_entry_modules(
.collect())
}
/// The chunks to preload for the `next/dynamic` imports of a page's client graph.
async fn page_next_dynamic_chunks(
endpoint: Vc<PageEndpoint>,
next_dynamic_imports: ReadRef<DynamicImportEntriesWithImporter>,
client_availability_info: AvailabilityInfo,
) -> Result<ResolvedVc<DynamicImportedChunks>> {
let this = endpoint.await?;
let project = this.pages_project.project();
let client_chunking_context = project.client_chunking_context();
// With a per-page module graph, a page's client graph is chained after `/_app`'s (see
// `client_module_graph`), so `next_dynamic_imports` also contains the `next/dynamic` imports
// of `/_app`. Those are loaded by `/_app`'s async loaders, which are chunked with `/_app`'s
// graph and availability, so preload them with the chunks `/_app` itself lists. Chunked with
// the page's availability, they would name chunks that don't match what those loaders
// request (and that may not be emitted at all).
if this.pathname == "/_app" || !*project.per_page_module_graph().await? {
return collect_next_dynamic_chunks(
endpoint.client_module_graph(),
client_chunking_context,
next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(client_availability_info),
)
.await;
}
let app_endpoint = this.pages_project.app_page_endpoint();
let app_module_graph = app_endpoint.client_module_graph();
let app_next_dynamic_imports = NextDynamicGraphs::new(app_module_graph, true)
.get_next_dynamic_imports_for_endpoint(app_endpoint.client_module())
.await?;
let app_dynamic_entries = app_next_dynamic_imports
.iter()
.map(|(dynamic_entry, _)| *dynamic_entry)
.collect::<FxHashSet<_>>();
let page_next_dynamic_imports = Vc::<DynamicImportEntriesWithImporter>::cell(
next_dynamic_imports
.iter()
.filter(|(dynamic_entry, _)| !app_dynamic_entries.contains(dynamic_entry))
.cloned()
.collect(),
)
.await?;
let page_chunks = collect_next_dynamic_chunks(
endpoint.client_module_graph(),
client_chunking_context,
page_next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(client_availability_info),
)
.await?;
let app_chunks = collect_next_dynamic_chunks(
app_module_graph,
client_chunking_context,
app_next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(
app_endpoint.client_chunk_group().await?.availability_info,
),
)
.await?;
let mut chunks = (*app_chunks.await?).clone();
chunks.extend(page_chunks.await?.iter().map(|(k, v)| (*k, *v)));
Ok(ResolvedVc::cell(chunks))
}
#[turbo_tasks::value_impl]
impl PageEndpoint {
#[turbo_tasks::function]
......@@ -1056,13 +1127,8 @@ impl PageEndpoint {
client_availability_info,
)) = next_dynamic_imports
{
collect_next_dynamic_chunks(
self.client_module_graph(),
project.client_chunking_context(),
next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(client_availability_info),
)
.await?
page_next_dynamic_chunks(self, next_dynamic_imports, client_availability_info)
.await?
} else {
DynamicImportedChunks::default().resolved_cell()
};
......
export const appShared = (s: string) => `app-shared:${s}`
export const lazyOnly = (s: string) => `lazy-only-marker:${s}`
import { appShared } from './app-shared'
import { lazyOnly } from './lazy-only'
import { pageShared } from './page-shared'
export function Lazy() {
return (
<p id="lazy">
{[appShared('lazy'), pageShared('lazy'), lazyOnly('lazy')].join(',')}
</p>
)
}
export const pageShared = (s: string) => `page-shared:${s}`
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// `_app` renders a `next/dynamic` component that shares a module with `/` (but not with `/other`).
// The component is loaded by `_app`'s own async loader on every page, so every page has to preload
// the same chunks, the ones that loader requests, regardless of what the page already loaded.
describe('pages-app-next-dynamic-preload', () => {
const { next } = nextTestSetup({
files: __dirname,
})
const pages = ['/', '/other']
// The `/_next/static` scripts and stylesheets (including preloads) in the SSR HTML, with their
// query strings (e.g. the deployment id).
async function getReferencedAssets(pathname: string) {
const $ = await next.render$(pathname)
const urls = $('script[src], link[href]')
.toArray()
.map((el) => $(el).attr('src') ?? $(el).attr('href') ?? '')
.filter((url) => /^\/_next\/static\/.+\.(?:js|css)(?:\?|$)/.test(url))
return [...new Set(urls)]
}
it.each(pages)(
'serves every asset referenced in the HTML of %s',
async (pathname) => {
const assets = await getReferencedAssets(pathname)
expect(assets.length).toBeGreaterThan(0)
const failed: string[] = []
for (const asset of assets) {
const res = await next.fetch(asset)
if (res.status !== 200) failed.push(`${res.status} ${asset}`)
}
expect(failed).toEqual([])
}
)
it.each(pages)(
'renders the _app next/dynamic component on %s',
async (pathname) => {
const browser = await next.browser(pathname)
await retry(async () => {
expect(await browser.elementByCss('#lazy').text()).toBe(
'app-shared:lazy,page-shared:lazy,lazy-only-marker:lazy'
)
})
expect(await browser.elementByCss('#app').text()).toBe('app-shared:app')
}
)
// @gate !turbopack || dev
it('preloads the same _app next/dynamic chunks on every page', async () => {
const preloadedChunks: Record<string, string[]> = {}
for (const pathname of pages) {
const chunks: string[] = []
for (const asset of await getReferencedAssets(pathname)) {
if (!/\.js(?:\?|$)/.test(asset)) continue
const res = await next.fetch(asset)
expect({ asset, status: res.status }).toEqual({ asset, status: 200 })
if ((await res.text()).includes('lazy-only-marker')) {
chunks.push(asset.split('?')[0])
}
}
preloadedChunks[pathname] = chunks.sort()
}
expect(preloadedChunks['/']).not.toEqual([])
expect(preloadedChunks['/other']).toEqual(preloadedChunks['/'])
})
})
import type { AppProps } from 'next/app'
import dynamic from 'next/dynamic'
import { appShared } from '../components/app-shared'
const Lazy = dynamic(() => import('../components/lazy').then((m) => m.Lazy))
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<p id="app">{appShared('app')}</p>
<Lazy />
<Component {...pageProps} />
</>
)
}
// Shared with `components/lazy`, which `_app` loads with `next/dynamic`: this page has already
// loaded it when `_app`'s dynamic import runs, `/other` hasn't.
import { pageShared } from '../components/page-shared'
export default function Page() {
return <p id="page">{pageShared('index')}</p>
}
export default function Page() {
return <p id="page">other</p>
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment