Unverified Commit 3dc93da2 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Improve tree shaking through Next.js module wrappers (#98638)

## What?

Extends the export-usage passthrough introduced by #98621 to the
transparent wrappers used for dynamic entries, server components, and
shared server utilities.

The existing reference-tree-shaking production fixture now covers each
wrapper and verifies that unused sibling exports do not remain in
Turbopack's server chunks.

## Why?

These wrappers forward another module's export surface, but previously
marked every target export as used. That kept otherwise unreachable
modules in production output and limited inner-graph tree shaking.

## How?

The dynamic-entry and server-component wrappers now pass their own
resolved export usage to their targets. The custom server-utility
reference reports the same passthrough binding usage while preserving
its shared chunking and merge behavior.

A public Turbopack constructor creates passthrough export-usage values
for references outside `turbopack-core`, consistent with the existing
constructors for other usage modes.

## Verification

- `cargo check -p next-core`
- `pnpm build-all`
- `pnpm test-start-turbo
test/production/app-dir/reference-tree-shaking/reference-tree-shaking.test.ts`
- `pnpm test-start-webpack
test/production/app-dir/reference-tree-shaking/reference-tree-shaking.test.ts`

<!-- NEXT_JS_LLM -->


<!-- fleet df1472be-5cd1-4bd6-9fab-4efc1defa4f9 -->
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent e3ababa0
...@@ -41,7 +41,7 @@ impl NextDynamicEntryModule { ...@@ -41,7 +41,7 @@ impl NextDynamicEntryModule {
Vc::upcast(SingleChunkableModuleReference::new( Vc::upcast(SingleChunkableModuleReference::new(
Vc::upcast(*self.module), Vc::upcast(*self.module),
rcstr!("next/dynamic reference"), rcstr!("next/dynamic reference"),
ExportUsage::all(), ExportUsage::passthrough(true),
)) ))
} }
} }
......
...@@ -65,7 +65,7 @@ impl NextServerComponentModule { ...@@ -65,7 +65,7 @@ impl NextServerComponentModule {
Vc::upcast(SingleChunkableModuleReference::new( Vc::upcast(SingleChunkableModuleReference::new(
Vc::upcast(*self.module), Vc::upcast(*self.module),
rcstr!("Next.js Server Component"), rcstr!("Next.js Server Component"),
ExportUsage::all(), ExportUsage::passthrough(true),
)) ))
} }
} }
......
...@@ -3,7 +3,10 @@ use std::sync::LazyLock; ...@@ -3,7 +3,10 @@ use std::sync::LazyLock;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use turbopack_core::{ use turbopack_core::{
chunk::ChunkingType, module::Module, reference::ModuleReference, resolve::ModuleResolveResult, chunk::ChunkingType,
module::Module,
reference::ModuleReference,
resolve::{BindingUsage, ExportUsage, ImportUsage, ModuleResolveResult},
}; };
#[turbo_tasks::value] #[turbo_tasks::value]
...@@ -37,4 +40,13 @@ impl ModuleReference for NextServerUtilityModuleReference { ...@@ -37,4 +40,13 @@ impl ModuleReference for NextServerUtilityModuleReference {
merge_tag: Some(NEXT_SERVER_UTILITY_MERGE_TAG.clone()), merge_tag: Some(NEXT_SERVER_UTILITY_MERGE_TAG.clone()),
}) })
} }
fn binding_usage(&self) -> BindingUsage {
BindingUsage {
import: ImportUsage::TopLevel,
export: ExportUsage::Passthrough {
namespace_object_may_escape: true,
},
}
}
} }
import { Server } from '../library/index.js' import { Server } from '../library/index.js'
import { UsedDynamic } from '../library/dynamic.js' with { 'turbopack-transition': 'next-dynamic' }
import { UsedServerComponent } from '../library/server-component.js' with { 'turbopack-transition': 'next-server-component' }
import { usedServerUtility } from '../library/server-utility.js' with { 'turbopack-transition': 'next-server-utility' }
export default function page() { export default function page() {
return <Server /> return (
<>
<Server />
<UsedDynamic />
<UsedServerComponent />
{usedServerUtility()}
</>
)
} }
import { unusedDynamic } from './unused-dynamic.js'
export function UsedDynamic() {
return 'This is Dynamic'
}
export function UnusedDynamic() {
return unusedDynamic()
}
import { unusedServerComponent } from './unused-server-component.js'
export function UsedServerComponent() {
return 'This is Server Component'
}
export function UnusedServerComponent() {
return unusedServerComponent()
}
import { unusedServerUtility } from './unused-server-utility.js'
export function usedServerUtility() {
return 'This is Server Utility'
}
export function unusedServerUtilityExport() {
return unusedServerUtility()
}
export function unusedDynamic() {
return 'unused-next-dynamic-export'
}
export function unusedServerComponent() {
return 'unused-next-server-component-export'
}
export function unusedServerUtility() {
return 'unused-next-server-utility-export'
}
...@@ -7,7 +7,11 @@ describe('reference-tree-shaking', () => { ...@@ -7,7 +7,11 @@ describe('reference-tree-shaking', () => {
it('Should apply removeUnusedImports tree shaking to client and server references', async () => { it('Should apply removeUnusedImports tree shaking to client and server references', async () => {
const res = await next.fetch('/') const res = await next.fetch('/')
expect(await res.text()).toContain('This is Server') const html = await res.text()
expect(html).toContain('This is Server')
expect(html).toContain('This is Dynamic')
expect(html).toContain('This is Server Component')
expect(html).toContain('This is Server Utility')
// Only Turbopack applies inner graph tree shaking here // Only Turbopack applies inner graph tree shaking here
if (process.env.IS_TURBOPACK_TEST) { if (process.env.IS_TURBOPACK_TEST) {
...@@ -22,4 +26,21 @@ describe('reference-tree-shaking', () => { ...@@ -22,4 +26,21 @@ describe('reference-tree-shaking', () => {
expect(clientReferences).not.toContain('library/client.js') expect(clientReferences).not.toContain('library/client.js')
} }
}) })
if (process.env.IS_TURBOPACK_TEST) {
it.each([
['NextDynamicEntryModule', 'unused-next-dynamic-export'],
['NextServerComponentModule', 'unused-next-server-component-export'],
['NextServerUtilityModule', 'unused-next-server-utility-export'],
])('tree shakes unused exports through %s', async (_module, marker) => {
const serverChunks = await next.readFiles(
'.next/server/chunks/ssr',
(filename) => filename.endsWith('.js')
)
expect(serverChunks.some((content) => content.includes(marker))).toBe(
false
)
})
}
}) })
...@@ -233,6 +233,14 @@ impl ExportUsage { ...@@ -233,6 +233,14 @@ impl ExportUsage {
pub fn named(name: RcStr) -> Vc<Self> { pub fn named(name: RcStr) -> Vc<Self> {
Self::Named(name).cell() Self::Named(name).cell()
} }
#[turbo_tasks::function]
pub fn passthrough(namespace_object_may_escape: bool) -> Vc<Self> {
Self::Passthrough {
namespace_object_may_escape,
}
.cell()
}
} }
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
......
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