Unverified Commit defac920 authored by Tim White's avatar Tim White Committed by GitHub

feat(turbopack): add chunkLoadingGlobal config option (#93488)

### What?

Adds a new `chunkLoadingGlobal` option to the `turbopack` config in
`next.config.js` that overrides the global variable name used for
Turbopack chunk loading (defaults to `TURBOPACK`).

```js
// next.config.js
module.exports = {
  turbopack: {
    chunkLoadingGlobal: 'myApp',
  },
}
```

### Why?

When multiple Turbopack-built apps run on the same page (e.g. horizontal
micro-frontends), they each try to use `globalThis.TURBOPACK` which
causes conflicts. This option allows each app to use its own isolated
global, mirroring webpack's `output.chunkLoadingGlobal`.

The `chunk_loading_global` method was already wired into Turbopack in
#88790 — this PR exposes it via Next.js config.

A reason is
[vercel/remote-components#239](https://github.com/vercel/remote-components/pull/239),
which uses this option to eliminate four brittle `globalThis.TURBOPACK`
regex rename transforms in the remote-components runtime. Those
transforms target Turbopack's internal variable naming and have already
required updates as Turbopack's output format evolved. With
`chunkLoadingGlobal` set at build time, Turbopack handles the renaming
natively and those transforms become unnecessary.

### How?

- `config-shared.ts` / `config-schema.ts` — adds `chunkLoadingGlobal?:
string` to `TurbopackOptions` with Zod validation
- `next_config.rs` — adds the field to `TurbopackConfig` and a
`turbopack_chunk_loading_global()` accessor
- `next_client/context.rs` — threads it through
`ClientChunkingContextOptions` and calls
`builder.chunk_loading_global()` when set
- `project.rs` — wires the config into the client chunking context
options

Only applies to the browser/client chunking context — server and edge
runtimes don't have this concept.

### Test plan

- `pnpm test-start-turbo
test/production/app-dir/turbopack-chunk-loading-global/turbopack-chunk-loading-global.test.ts`

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 91eb8316
......@@ -1594,6 +1594,7 @@ impl Project {
css_url_suffix,
hash_salt: self.next_config().output_hash_salt().to_resolved().await?,
cross_origin: self.next_config().cross_origin(),
chunk_loading_global: self.next_config().turbopack_chunk_loading_global(),
}))
}
......
......@@ -482,6 +482,7 @@ pub struct ClientChunkingContextOptions {
pub css_url_suffix: Vc<Option<RcStr>>,
pub hash_salt: ResolvedVc<RcStr>,
pub cross_origin: Vc<CrossOrigin>,
pub chunk_loading_global: Vc<Option<RcStr>>,
}
#[turbo_tasks::function]
......@@ -510,6 +511,7 @@ pub async fn get_client_chunking_context(
css_url_suffix,
hash_salt,
cross_origin,
chunk_loading_global,
} = options;
let next_mode = mode.await?;
......@@ -556,6 +558,10 @@ pub async fn get_client_chunking_context(
static_suffix: css_url_suffix.to_resolved().await?,
});
if let Some(g) = &*chunk_loading_global.await? {
builder = builder.chunk_loading_global(g.clone());
}
if next_mode.is_development() {
builder = builder
.hot_module_replacement()
......
......@@ -592,6 +592,7 @@ pub struct TurbopackConfig {
pub resolve_alias: Option<FxIndexMap<RcStr, JsonValue>>,
pub resolve_extensions: Option<Vec<RcStr>>,
pub debug_ids: Option<bool>,
pub chunk_loading_global: Option<RcStr>,
/// Issue patterns to ignore (suppress) from Turbopack output.
#[serde(default)]
pub ignore_issue: Option<Vec<TurbopackIgnoreIssueRule>>,
......@@ -2296,6 +2297,15 @@ impl NextConfig {
)
}
#[turbo_tasks::function]
pub fn turbopack_chunk_loading_global(&self) -> Vc<Option<RcStr>> {
Vc::cell(
self.turbopack
.as_ref()
.and_then(|t| t.chunk_loading_global.clone()),
)
}
#[turbo_tasks::function]
pub fn typescript_tsconfig_path(&self) -> Result<Vc<Option<RcStr>>> {
Ok(Vc::cell(
......
......@@ -176,6 +176,7 @@ const zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({
resolveExtensions: z.array(z.string()).optional(),
root: z.string().optional(),
debugIds: z.boolean().optional(),
chunkLoadingGlobal: z.string().optional(),
ignoreIssue: z
.array(
z.object({
......
......@@ -242,6 +242,16 @@ export interface TurbopackOptions {
title?: string | RegExp
description?: string | RegExp
}>
/**
* Override the global variable name used for
* chunk loading. Useful when multiple Turbopack-built apps run on the same
* page (e.g. horizontal micro-frontends) to avoid `globalThis.TURBOPACK`
* conflicts.
*
* @see https://webpack.js.org/configuration/output/#outputchunkloadingglobal
*/
chunkLoadingGlobal?: string
}
export interface WebpackConfigContext {
......
......@@ -1012,6 +1012,13 @@ function assignDefaultsAndValidate(
}
}
if (result?.turbopack?.chunkLoadingGlobal) {
const g = result.turbopack.chunkLoadingGlobal
if (!g.startsWith('TURBOPACK_')) {
result.turbopack.chunkLoadingGlobal = `TURBOPACK_${g}`
}
}
if (
result.experimental.runtimeServerDeploymentId == null &&
phase === PHASE_PRODUCTION_BUILD &&
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import { useState } from 'react'
export default function Page() {
const [count, setCount] = useState(0)
return (
<div>
<p id="count">{count}</p>
<button onClick={() => setCount((c) => c + 1)}>increment</button>
</div>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
turbopack: {
chunkLoadingGlobal: 'myApp',
},
}
module.exports = nextConfig
import fs from 'fs'
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
function collectJsFiles(dir: string): string[] {
if (!fs.existsSync(dir)) return []
return fs
.readdirSync(dir, { recursive: true, encoding: 'utf8' })
.flatMap((entry) => {
const full = path.join(dir, entry)
return entry.endsWith('.js') && fs.statSync(full).isFile() ? [full] : []
})
}
describe('turbopack-chunk-loading-global', () => {
const { next, isNextDeploy, isTurbopack } = nextTestSetup({
files: __dirname,
})
;(isNextDeploy || !isTurbopack ? describe.skip : describe)(
'chunk output',
() => {
it('uses the custom global name and drops the default TURBOPACK global', async () => {
const staticDir = path.join(next.testDir, '.next/static')
const jsFiles = collectJsFiles(staticDir)
expect(jsFiles.length).toBeGreaterThan(0)
const allContent = jsFiles
.map((f) => fs.readFileSync(f, 'utf8'))
.join('\n')
// Custom global must be used for chunk loading (auto-prefixed with TURBOPACK_)
expect(allContent).toContain('globalThis.TURBOPACK_myApp')
// Bare default TURBOPACK global must not appear — if it does,
// chunkLoadingGlobal was ignored by the Rust layer
expect(allContent).not.toMatch(/globalThis\.TURBOPACK(?!_)/)
})
}
)
describe('runtime behavior', () => {
it('renders content and handles interactions after hydration', async () => {
const browser = await next.browser('/')
// Initial render
expect(await browser.elementByCss('#count').text()).toBe('0')
// Click increments — proves chunks loaded and JS executed correctly
await browser.elementByCss('button').click()
expect(await browser.elementByCss('#count').text()).toBe('1')
await browser.elementByCss('button').click()
expect(await browser.elementByCss('#count').text()).toBe('2')
})
})
})
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