Unverified Commit 61bf6f63 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Turbopack: Fix next/font preloading for page.mdx (#88848)

## What?

This PR fixes font preloading for MDX pages in Turbopack and adds an e2e
test to verify the fix.

## Why?

When using `next/font` with MDX pages, font preloading was failing with
Turbopack because the LoaderTree was storing the **transformed module
path** instead of the **original source path**.

## The Bug

In Turbopack, MDX files are transformed by adding a `.tsx` extension:
- Source file: `app/page.mdx`
- After transform: `app/page.mdx.tsx`

The `create_module_tuple_code` function in `base_loader_tree.rs` was
using `module.ident().path()` (the transformed path) instead of the
original `path` parameter.

This caused a mismatch at runtime:
- Font manifest key: `[project]/app/page`
- LoaderTree stored: `[project]/app/page.mdx.tsx`
- After stripping `.tsx`: `[project]/app/page.mdx`
- **No match** → fonts not preloaded

## The Fix

Changed `crates/next-core/src/base_loader_tree.rs` to use the original
source path:

```rust
// Before
let module_path = module.ident().path().to_string().await?;

// After
let module_path = path.value_to_string().await?;
```

Now the LoaderTree stores `[project]/app/page.mdx`, which after
stripping `.mdx` at runtime becomes `[project]/app/page`, matching the
font manifest key.

## Test

Added `test/e2e/app-dir/mdx-font-preload/` which verifies:
1. MDX page renders correctly
2. Font class from layout is applied
3. Font is correctly preloaded

## How I tested these changes

```bash
pnpm test-start-turbo test/e2e/app-dir/mdx-font-preload/mdx-font-preload.test.ts
```

---------
Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 85d043a6
use anyhow::Result; use anyhow::Result;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexMap, ResolvedVc, ValueToString, Vc}; use turbo_tasks::{FxIndexMap, ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::{ModuleAssetContext, transition::Transition}; use turbopack::{ModuleAssetContext, transition::Transition};
use turbopack_core::{ use turbopack_core::{
...@@ -115,7 +115,10 @@ impl BaseLoaderTreeBuilder { ...@@ -115,7 +115,10 @@ impl BaseLoaderTreeBuilder {
self.inner_assets self.inner_assets
.insert(format!("MODULE_{i}").into(), module); .insert(format!("MODULE_{i}").into(), module);
let module_path = module.ident().path().to_string().await?; // Use the original source path, not the transformed module path.
// This is important for MDX files where page.mdx becomes page.mdx.tsx after
// transformation, but the font manifest uses the original source path.
let module_path = path.value_to_string().await?;
Ok(format!( Ok(format!(
"[{identifier}, {path}]", "[{identifier}, {path}]",
......
...@@ -405,8 +405,12 @@ async fn build_manifest( ...@@ -405,8 +405,12 @@ async fn build_manifest(
// per layout segment chunks need to be emitted into the manifest too // per layout segment chunks need to be emitted into the manifest too
for (server_component, client_assets) in layout_segment_client_chunks.iter() { for (server_component, client_assets) in layout_segment_client_chunks.iter() {
// Use source_path() to get the original source path (e.g., page.mdx) instead of
// server_path() which returns the transformed path (e.g., page.mdx.tsx).
// This ensures the manifest key matches what the LoaderTree stores and what
// the runtime looks up after stripping one extension.
let server_component_name = server_component let server_component_name = server_component
.server_path() .source_path()
.await? .await?
.with_extension("") .with_extension("")
.value_to_string() .value_to_string()
......
...@@ -30,15 +30,35 @@ use super::server_component_reference::NextServerComponentModuleReference; ...@@ -30,15 +30,35 @@ use super::server_component_reference::NextServerComponentModuleReference;
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct NextServerComponentModule { pub struct NextServerComponentModule {
pub module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, pub module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
/// The original source path before any transformations (e.g., page.mdx before it becomes
/// page.mdx.tsx). This is used to generate consistent manifest keys that match what the
/// LoaderTree stores.
source_path: FileSystemPath,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl NextServerComponentModule { impl NextServerComponentModule {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new(module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>) -> Vc<Self> { pub fn new(
NextServerComponentModule { module }.cell() module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
source_path: FileSystemPath,
) -> Vc<Self> {
NextServerComponentModule {
module,
source_path,
}
.cell()
}
/// Returns the original source path (before transformations like MDX -> MDX.tsx).
/// Use this for manifest key generation to match the LoaderTree paths.
#[turbo_tasks::function]
pub fn source_path(&self) -> Vc<FileSystemPath> {
self.source_path.clone().cell()
} }
/// Returns the transformed module path (e.g., page.mdx.tsx for MDX files).
/// This is the path of the actual compiled module.
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn server_path(&self) -> Vc<FileSystemPath> { pub fn server_path(&self) -> Vc<FileSystemPath> {
self.module.ident().path() self.module.ident().path()
......
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use turbo_tasks::Vc; use turbo_tasks::{ResolvedVc, Vc};
use turbopack::{ModuleAssetContext, transition::Transition}; use turbopack::{ModuleAssetContext, transition::Transition};
use turbopack_core::module::Module; use turbopack_core::{
context::{AssetContext, ProcessResult},
reference_type::ReferenceType,
source::Source,
};
use turbopack_ecmascript::chunk::EcmascriptChunkPlaceable; use turbopack_ecmascript::chunk::EcmascriptChunkPlaceable;
use super::server_component_module::NextServerComponentModule; use super::server_component_module::NextServerComponentModule;
...@@ -26,18 +30,40 @@ impl NextServerComponentTransition { ...@@ -26,18 +30,40 @@ impl NextServerComponentTransition {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Transition for NextServerComponentTransition { impl Transition for NextServerComponentTransition {
/// Override process to capture the original source path before transformation.
/// This is important for MDX files where page.mdx becomes page.mdx.tsx after
/// transformation, but we need the original path for manifest key generation.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn process_module( async fn process(
self: Vc<Self>, self: Vc<Self>,
module: Vc<Box<dyn Module>>, source: Vc<Box<dyn Source>>,
_context: Vc<ModuleAssetContext>, module_asset_context: Vc<ModuleAssetContext>,
) -> Result<Vc<Box<dyn Module>>> { reference_type: ReferenceType,
let Some(module) = ) -> Result<Vc<ProcessResult>> {
Vc::try_resolve_sidecast::<Box<dyn EcmascriptChunkPlaceable>>(module).await? // Capture the original source path before any transformation
else { let source_path = source.ident().path().owned().await?;
bail!("not an ecmascript module");
}; let source = self.process_source(source);
let module_asset_context = self.process_context(module_asset_context);
Ok(Vc::upcast(NextServerComponentModule::new(module)))
Ok(
match &*module_asset_context.process(source, reference_type).await? {
ProcessResult::Module(module) => {
let Some(module) =
ResolvedVc::try_sidecast::<Box<dyn EcmascriptChunkPlaceable>>(*module)
else {
bail!("not an ecmascript module");
};
// Create the server component module with the original source path
let server_component = NextServerComponentModule::new(*module, source_path);
ProcessResult::Module(ResolvedVc::upcast(server_component.to_resolved().await?))
.cell()
}
ProcessResult::Unknown(source) => ProcessResult::Unknown(*source).cell(),
ProcessResult::Ignore => ProcessResult::Ignore.cell(),
},
)
} }
} }
import localFont from 'next/font/local'
const myFont = localFont({
src: '../fonts/font1_roboto.woff2',
variable: '--font-my-font',
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={myFont.className}>{children}</body>
</html>
)
}
# MDX Page
This is an MDX page with font preloading.
The font should be preloaded from the layout.
export function useMDXComponents(components: Record<string, unknown>) {
return {
...components,
}
}
import { nextTestSetup } from 'e2e-utils'
describe('mdx-font-preload', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
'@next/mdx': 'canary',
'@mdx-js/loader': '^2.2.1',
'@mdx-js/react': '^2.2.1',
},
})
it('should render MDX page', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('h1').text()).toBe('MDX Page')
expect(await browser.elementByCss('p').text()).toBe(
'This is an MDX page with font preloading.'
)
})
it('should apply font class from layout', async () => {
const browser = await next.browser('/')
const fontFamily = await browser.eval(
'getComputedStyle(document.body).fontFamily'
)
expect(fontFamily).toMatch(/myFont/)
})
it('should preload font from layout on MDX page', async () => {
const browser = await next.browser('/')
// Check for font preload link in DOM
const fontPreloadLinks = await browser.elementsByCss('link[as="font"]')
expect(fontPreloadLinks.length).toBeGreaterThan(0)
// Verify the preload link attributes
const rel = await fontPreloadLinks[0].getAttribute('rel')
const as = await fontPreloadLinks[0].getAttribute('as')
const type = await fontPreloadLinks[0].getAttribute('type')
const crossorigin = await fontPreloadLinks[0].getAttribute('crossorigin')
expect(rel).toBe('preload')
expect(as).toBe('font')
expect(type).toBe('font/woff2')
expect(crossorigin).toBe('')
})
})
import nextMDX from '@next/mdx'
const withMDX = nextMDX({
extension: /\.mdx?$/,
})
/** @type {import('next').NextConfig} */
const nextConfig = {
pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'mdx'],
}
export default withMDX(nextConfig)
...@@ -102,16 +102,16 @@ pub trait Transition { ...@@ -102,16 +102,16 @@ pub trait Transition {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn process( async fn process(
self: Vc<Self>, self: Vc<Self>,
asset: Vc<Box<dyn Source>>, source: Vc<Box<dyn Source>>,
module_asset_context: Vc<ModuleAssetContext>, module_asset_context: Vc<ModuleAssetContext>,
reference_type: ReferenceType, reference_type: ReferenceType,
) -> Result<Vc<ProcessResult>> { ) -> Result<Vc<ProcessResult>> {
let asset = self.process_source(asset); let source = self.process_source(source);
let module_asset_context = self.process_context(module_asset_context); let module_asset_context = self.process_context(module_asset_context);
let asset = asset.to_resolved().await?; let source = source.to_resolved().await?;
Ok(match &*module_asset_context Ok(match &*module_asset_context
.process_default(asset, reference_type) .process_default(source, reference_type)
.await? .await?
.await? .await?
{ {
......
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