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 { ...@@ -151,42 +151,49 @@ impl EcmascriptDevChunkListContent {
.map(|s| s.as_str()) .map(|s| s.as_str())
.collect::<Vec<_>>(); .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(); let mut code = CodeBuilder::default();
if this.esm_chunks { if this.esm_chunks {
// In ESM mode, chunks are loaded via import() which reads the default // In ESM mode, export the chunk list data as the default export.
// export. Emit an empty factories list so the runtime can handle this // The ESM runtime backend detects this (via the `chunkList` property)
// chunk without errors. // and calls registerChunkList instead of installCompressedModuleFactories.
write!(code, "export default [];\n")?; // 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())) Ok(Code::cell(code.build()))
} }
} }
......
...@@ -15,12 +15,14 @@ ...@@ -15,12 +15,14 @@
/// <reference path="../../../browser/runtime/base/runtime-base.ts" /> /// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime/runtime-types.d.ts" /> /// <reference path="../../../shared/runtime/runtime-types.d.ts" />
// In dev mode, addModuleToChunk is defined by dev-base.ts (concatenated into // In dev mode, addModuleToChunk and registerChunkList are defined by
// the same IIFE). Declare it optional so the typeof check works in production. // 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( declare function addModuleToChunk(
moduleId: ModuleId, moduleId: ModuleId,
chunkPath: ChunkPath chunkPath: ChunkPath
): void ): void
declare function registerChunkList(chunkList: ChunkList): void
function getAssetSuffixFromScriptSrc() { function getAssetSuffixFromScriptSrc() {
// TURBOPACK_ASSET_SUFFIX is set in web workers. // TURBOPACK_ASSET_SUFFIX is set in web workers.
...@@ -178,21 +180,35 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map() ...@@ -178,21 +180,35 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
// Use dynamic import() to load JS chunks as ES modules. // Use dynamic import() to load JS chunks as ES modules.
// The chunk exports `default` as CompressedModuleFactories (offset=0).
import(/* turbopackIgnore: true */ chunkUrl) import(/* turbopackIgnore: true */ chunkUrl)
.then(({ default: factories }) => { .then(({ default: data }) => {
const chunkPath = getPathFromScript(chunkUrl as ChunkPath) if (data && data.chunkList) {
installCompressedModuleFactories( // Chunk list: the default export is { chunkList: { chunks, source } }.
factories as CompressedModuleFactories, // In dev mode, register it for HMR tracking. In production the
/* offset= */ 0, // registerChunkList function doesn't exist — just resolve.
moduleFactories, if (typeof registerChunkList === 'function') {
// Pass the addModuleToChunk callback for HMR tracking in dev mode. const chunkPath = getPathFromScript(chunkUrl as ChunkPath)
// In production, addModuleToChunk is not defined (dev-base.ts is not registerChunkList({
// concatenated), so the typeof check makes this safe. script: chunkPath,
typeof addModuleToChunk !== 'undefined' chunks: data.chunkList.chunks,
? (id: ModuleId) => addModuleToChunk(id, chunkPath) source: data.chunkList.source,
: undefined })
) }
} 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() resolver.resolve()
}) })
.catch((err: Error) => resolver.reject(err)) .catch((err: Error) => resolver.reject(err))
......
...@@ -924,8 +924,9 @@ function registerChunk(registration) { ...@@ -924,8 +924,9 @@ function registerChunk(registration) {
* It will be appended to the base runtime code. * It will be appended to the base runtime code.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../../browser/runtime/base/runtime-base.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime/runtime-types.d.ts" /> /// <reference path="../../../shared/runtime/runtime-types.d.ts" />
// In dev mode, addModuleToChunk is defined by dev-base.ts (concatenated into // In dev mode, addModuleToChunk and registerChunkList are defined by
// the same IIFE). Declare it optional so the typeof check works in production. // 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() { function getAssetSuffixFromScriptSrc() {
// TURBOPACK_ASSET_SUFFIX is set in web workers. // TURBOPACK_ASSET_SUFFIX is set in web workers.
if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX; if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX;
...@@ -1033,13 +1034,27 @@ let BACKEND; ...@@ -1033,13 +1034,27 @@ let BACKEND;
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
// Use dynamic import() to load JS chunks as ES modules. // Use dynamic import() to load JS chunks as ES modules.
// The chunk exports `default` as CompressedModuleFactories (offset=0). import(/* turbopackIgnore: true */ chunkUrl).then(({ default: data })=>{
import(/* turbopackIgnore: true */ chunkUrl).then(({ default: factories })=>{ if (data && data.chunkList) {
const chunkPath = getPathFromScript(chunkUrl); // Chunk list: the default export is { chunkList: { chunks, source } }.
installCompressedModuleFactories(factories, /* offset= */ 0, moduleFactories, // Pass the addModuleToChunk callback for HMR tracking in dev mode. // In dev mode, register it for HMR tracking. In production the
// In production, addModuleToChunk is not defined (dev-base.ts is not // registerChunkList function doesn't exist — just resolve.
// concatenated), so the typeof check makes this safe. if (typeof registerChunkList === 'function') {
typeof addModuleToChunk !== 'undefined' ? (id)=>addModuleToChunk(id, chunkPath) : undefined); 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(); resolver.resolve();
}).catch((err)=>resolver.reject(err)); }).catch((err)=>resolver.reject(err));
} else { } 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