Commit a5c6e1f4 authored by Tobias Koppers's avatar Tobias Koppers

ESM chunk list: export data instead of using globals

In ESM mode, HMR chunk list files now export their data as
`export default { chunkList: { chunks, source } }` instead of
pushing to `globalThis[TURBOPACK_CHUNK_LISTS]`. The ESM runtime
backend detects this shape in doLoadChunk and calls registerChunkList
directly, avoiding global state for chunk list registration.
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent 41d90359
......@@ -151,42 +151,49 @@ impl EcmascriptDevChunkListContent {
.map(|s| s.as_str())
.collect::<Vec<_>>();
let script_or_path = match &this.current_chunk_method {
CurrentChunkMethodWithData::StringLiteral(path) => Either::Left(StringifyJs(path)),
CurrentChunkMethodWithData::DocumentCurrentScript => {
Either::Right(CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR)
}
};
let mut code = CodeBuilder::default();
if this.esm_chunks {
// In ESM mode, chunks are loaded via import() which reads the default
// export. Emit an empty factories list so the runtime can handle this
// chunk without errors.
write!(code, "export default [];\n")?;
// In ESM mode, export the chunk list data as the default export.
// The ESM runtime backend detects this (via the `chunkList` property)
// and calls registerChunkList instead of installCompressedModuleFactories.
// This avoids relying on globalThis for chunk list registration.
writedoc!(
code,
r#"
export default {{ chunkList: {{ chunks: {chunks}, source: {source} }} }};
"#,
chunks = StringifyJs(&chunks),
source = StringifyJs(&this.source),
)?;
} else {
let script_or_path = match &this.current_chunk_method {
CurrentChunkMethodWithData::StringLiteral(path) => Either::Left(StringifyJs(path)),
CurrentChunkMethodWithData::DocumentCurrentScript => {
Either::Right(CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR)
}
};
// When loaded, JS chunks must register themselves with the `TURBOPACK` global
// variable. Similarly, we register the chunk list with the
// `{chunk_loading_global}_CHUNK_LISTS` global variable.
let chunk_lists_global = format!("{}_CHUNK_LISTS", this.chunk_loading_global);
writedoc!(
code,
// `||=` would be better but we need to be es2020 compatible
//`x || (x = default)` is better than `x = x || default` simply because we avoid _writing_ the property in the common case.
r#"
(globalThis[{chunk_lists_global}] || (globalThis[{chunk_lists_global}] = [])).push({{
script: {script_or_path},
chunks: {chunks},
source: {source}
}});
"#,
chunk_lists_global = StringifyJs(&chunk_lists_global),
chunks = StringifyJs(&chunks),
source = StringifyJs(&this.source),
)?;
}
// When loaded, JS chunks must register themselves with the `TURBOPACK` global
// variable. Similarly, we register the chunk list with the
// `{chunk_loading_global}_CHUNK_LISTS` global variable.
let chunk_lists_global = format!("{}_CHUNK_LISTS", this.chunk_loading_global);
writedoc!(
code,
// `||=` would be better but we need to be es2020 compatible
//`x || (x = default)` is better than `x = x || default` simply because we avoid _writing_ the property in the common case.
r#"
(globalThis[{chunk_lists_global}] || (globalThis[{chunk_lists_global}] = [])).push({{
script: {script_or_path},
chunks: {chunks},
source: {source}
}});
"#,
chunk_lists_global = StringifyJs(&chunk_lists_global),
chunks = StringifyJs(&chunks),
source = StringifyJs(&this.source),
)?;
Ok(Code::cell(code.build()))
}
}
......
......@@ -15,12 +15,14 @@
/// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime/runtime-types.d.ts" />
// In dev mode, addModuleToChunk is defined by dev-base.ts (concatenated into
// the same IIFE). Declare it optional so the typeof check works in production.
// In dev mode, addModuleToChunk and registerChunkList are defined by
// dev-base.ts (concatenated into the same IIFE). Declare them optional so the
// typeof checks work in production builds where dev-base.ts is absent.
declare function addModuleToChunk(
moduleId: ModuleId,
chunkPath: ChunkPath
): void
declare function registerChunkList(chunkList: ChunkList): void
function getAssetSuffixFromScriptSrc() {
// TURBOPACK_ASSET_SUFFIX is set in web workers.
......@@ -178,21 +180,35 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
}
} else if (isJs(chunkUrl)) {
// Use dynamic import() to load JS chunks as ES modules.
// The chunk exports `default` as CompressedModuleFactories (offset=0).
import(/* turbopackIgnore: true */ chunkUrl)
.then(({ default: factories }) => {
const chunkPath = getPathFromScript(chunkUrl as ChunkPath)
installCompressedModuleFactories(
factories as CompressedModuleFactories,
/* offset= */ 0,
moduleFactories,
// Pass the addModuleToChunk callback for HMR tracking in dev mode.
// In production, addModuleToChunk is not defined (dev-base.ts is not
// concatenated), so the typeof check makes this safe.
typeof addModuleToChunk !== 'undefined'
? (id: ModuleId) => addModuleToChunk(id, chunkPath)
: undefined
)
.then(({ default: data }) => {
if (data && data.chunkList) {
// Chunk list: the default export is { chunkList: { chunks, source } }.
// In dev mode, register it for HMR tracking. In production the
// registerChunkList function doesn't exist — just resolve.
if (typeof registerChunkList === 'function') {
const chunkPath = getPathFromScript(chunkUrl as ChunkPath)
registerChunkList({
script: chunkPath,
chunks: data.chunkList.chunks,
source: data.chunkList.source,
})
}
} else {
// Module factories: the default export is CompressedModuleFactories.
const chunkPath = getPathFromScript(chunkUrl as ChunkPath)
installCompressedModuleFactories(
data as CompressedModuleFactories,
/* offset= */ 0,
moduleFactories,
// Pass the addModuleToChunk callback for HMR tracking in dev mode.
// In production, addModuleToChunk is not defined (dev-base.ts is not
// concatenated), so the typeof check makes this safe.
typeof addModuleToChunk !== 'undefined'
? (id: ModuleId) => addModuleToChunk(id, chunkPath)
: undefined
)
}
resolver.resolve()
})
.catch((err: Error) => resolver.reject(err))
......
......@@ -924,8 +924,9 @@ function registerChunk(registration) {
* It will be appended to the base runtime code.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime/runtime-types.d.ts" />
// In dev mode, addModuleToChunk is defined by dev-base.ts (concatenated into
// the same IIFE). Declare it optional so the typeof check works in production.
// In dev mode, addModuleToChunk and registerChunkList are defined by
// dev-base.ts (concatenated into the same IIFE). Declare them optional so the
// typeof checks work in production builds where dev-base.ts is absent.
function getAssetSuffixFromScriptSrc() {
// TURBOPACK_ASSET_SUFFIX is set in web workers.
if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX;
......@@ -1033,13 +1034,27 @@ let BACKEND;
}
} else if (isJs(chunkUrl)) {
// Use dynamic import() to load JS chunks as ES modules.
// The chunk exports `default` as CompressedModuleFactories (offset=0).
import(/* turbopackIgnore: true */ chunkUrl).then(({ default: factories })=>{
const chunkPath = getPathFromScript(chunkUrl);
installCompressedModuleFactories(factories, /* offset= */ 0, moduleFactories, // Pass the addModuleToChunk callback for HMR tracking in dev mode.
// In production, addModuleToChunk is not defined (dev-base.ts is not
// concatenated), so the typeof check makes this safe.
typeof addModuleToChunk !== 'undefined' ? (id)=>addModuleToChunk(id, chunkPath) : undefined);
import(/* turbopackIgnore: true */ chunkUrl).then(({ default: data })=>{
if (data && data.chunkList) {
// Chunk list: the default export is { chunkList: { chunks, source } }.
// In dev mode, register it for HMR tracking. In production the
// registerChunkList function doesn't exist — just resolve.
if (typeof registerChunkList === 'function') {
const chunkPath = getPathFromScript(chunkUrl);
registerChunkList({
script: chunkPath,
chunks: data.chunkList.chunks,
source: data.chunkList.source
});
}
} else {
// Module factories: the default export is CompressedModuleFactories.
const chunkPath = getPathFromScript(chunkUrl);
installCompressedModuleFactories(data, /* offset= */ 0, moduleFactories, // Pass the addModuleToChunk callback for HMR tracking in dev mode.
// In production, addModuleToChunk is not defined (dev-base.ts is not
// concatenated), so the typeof check makes this safe.
typeof addModuleToChunk !== 'undefined' ? (id)=>addModuleToChunk(id, chunkPath) : undefined);
}
resolver.resolve();
}).catch((err)=>resolver.reject(err));
} else {
......
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