Unverified Commit eab71fd9 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

refactor(turbopack): address federation review feedback

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent a65ff58e
'use client'
import dynamic from 'next/dynamic'
import { useEffect, useState } from 'react'
const RemoteComponent = dynamic(
// @ts-expect-error -- provided by Module Federation at runtime
() => import('catalog/component'),
{ ssr: false, loading: () => <p>loading remote component</p> }
)
export function RemoteMessage() {
const [message, setMessage] = useState('loading')
const [workerMessage, setWorkerMessage] = useState('loading')
......@@ -44,6 +51,7 @@ export function RemoteMessage() {
return (
<>
<p id="remote-message">{message}</p>
<RemoteComponent />
<p id="worker-message">{workerMessage}</p>
<p id="remote-script-count">{scriptCount}</p>
</>
......
import React from 'react'
export default function WebpackRemoteComponent() {
return React.createElement(
'p',
{ id: 'remote-react-component' },
'next/dynamic from webpack remote'
)
}
......@@ -31,6 +31,7 @@ async function buildRemote(
name: worker ? 'workerCatalog' : 'catalog',
filename: 'remoteEntry.js',
exposes: {
'./component': './component.js',
'./message': './message.js',
},
shared: {
......@@ -103,6 +104,9 @@ describeTurbopack('turbopack module federation with a webpack remote', () => {
expect(await browser.elementByCss('#remote-message').text()).toBe(
'hello from Turbopack host sharing'
)
expect(await browser.elementByCss('#remote-react-component').text()).toBe(
'next/dynamic from webpack remote'
)
expect(await browser.elementByCss('#worker-message').text()).toBe(
'hello from Turbopack host sharing'
)
......
......@@ -454,7 +454,7 @@ function resolvePathFromModule(
.exports as Exports
return exported?.default ?? exported
}
browserContextPrototype.R = resolvePathFromModule
browserContextPrototype.S = resolvePathFromModule
/**
* no-op for browser
......
......@@ -24,7 +24,7 @@ const nodeContextPrototype = Context.prototype as TurbopackNodeBuildContext
nodeContextPrototype.q = exportUrl
nodeContextPrototype.c = moduleCache
nodeContextPrototype.R = resolvePathFromModule
nodeContextPrototype.S = resolvePathFromModule
nodeContextPrototype.C = clearChunkCache
function instantiateModule(
......
......@@ -29,7 +29,7 @@ const nodeDevContextPrototype =
nodeDevContextPrototype.q = exportUrl
nodeDevContextPrototype.c = moduleCache
nodeDevContextPrototype.R = resolvePathFromModule
nodeDevContextPrototype.S = resolvePathFromModule
nodeDevContextPrototype.C = clearChunkCache
markDevModulesLoaded = true
......
......@@ -175,7 +175,8 @@ interface TurbopackBaseContext<M> {
m: Module
c: ModuleCache<M>
M: ModuleFactories
S: ModuleFederationRuntimeState
R: ModuleFederationRuntimeState
S: ResolvePathFromModule
l: LoadChunk
L: LoadChunkByUrl
h: GetChunkRelativeURL
......
......@@ -79,7 +79,7 @@ function Context(
}
const contextPrototype = Context.prototype as TurbopackBaseContext<Module>
contextPrototype.M = moduleFactories
contextPrototype.S = {
contextPrototype.R = {
shareScopes: Object.create(null),
initScopes: Object.create(null),
remoteInitializations: Object.create(null),
......
......@@ -77,7 +77,7 @@ pub const TURBOPACK_EXPORT_URL: &TurbopackRuntimeFunctionShortcut = make_shortcu
pub const TURBOPACK_EXPORT_NAMESPACE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("n");
pub const TURBOPACK_CACHE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("c");
pub const TURBOPACK_MODULES: &TurbopackRuntimeFunctionShortcut = make_shortcut!("M");
pub const TURBOPACK_MODULE_FEDERATION: &TurbopackRuntimeFunctionShortcut = make_shortcut!("S");
pub const TURBOPACK_MODULE_FEDERATION: &TurbopackRuntimeFunctionShortcut = make_shortcut!("R");
pub const TURBOPACK_LOAD: &TurbopackRuntimeFunctionShortcut = make_shortcut!("l");
pub const TURBOPACK_LOAD_BY_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("L");
pub const TURBOPACK_CLEAR_CHUNK_CACHE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("C");
......@@ -85,7 +85,7 @@ pub const TURBOPACK_DYNAMIC: &TurbopackRuntimeFunctionShortcut = make_shortcut!(
pub const TURBOPACK_RESOLVE_ABSOLUTE_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("P");
pub const TURBOPACK_RESOLVE_FILE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("F");
pub const TURBOPACK_RELATIVE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("U");
pub const TURBOPACK_RESOLVE_MODULE_ID_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("R");
pub const TURBOPACK_RESOLVE_MODULE_ID_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("S");
pub const TURBOPACK_ASYNC_MODULE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("a");
pub const TURBOPACK_EXTERNAL_REQUIRE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("x");
pub const TURBOPACK_EXTERNAL_IMPORT: &TurbopackRuntimeFunctionShortcut = make_shortcut!("y");
......
......@@ -8,7 +8,7 @@ function createIsolatedRuntime(runtimePath, sourcePath, chunkPath, moduleId) {
const createRuntime = eval('require')(runtimePath)
fs.writeFileSync(
chunkPath,
`module.exports = [${JSON.stringify(moduleId)}, function (context, module) { module.exports = context.S }];\n`
`module.exports = [${JSON.stringify(moduleId)}, function (context, module) { module.exports = context.R }];\n`
)
const runtime = createRuntime(sourcePath)
runtime.c(chunkPath)
......
......@@ -2,6 +2,7 @@ use anyhow::Result;
use turbo_tasks::ResolvedVc;
use turbo_tasks_fs::{FileContent, FileSystemPath};
use turbopack_core::{asset::AssetContent, source::Source, virtual_source::VirtualSource};
use turbopack_ecmascript::utils::StringifyJs;
use crate::module_federation::config::ModuleFederationConfig;
......@@ -20,12 +21,12 @@ pub async fn module_federation_container_source(
let imports = expose
.imports
.iter()
.map(|request| format!("import({})", serde_json::to_string(request).unwrap()))
.map(|request| format!("import({})", StringifyJs(request)))
.collect::<Vec<_>>()
.join(", ");
module_entries.push(format!(
"{}: () => Promise.all([{}]).then((modules) => () => modules[modules.length - 1])",
serde_json::to_string(&expose.request)?,
StringifyJs(&expose.request),
imports
));
}
......@@ -44,14 +45,13 @@ pub async fn module_federation_container_source(
eager: {eager}
}};"#,
index = registrations.len(),
key = serde_json::to_string(&shared.share_key)?,
version = serde_json::to_string(version)?,
import = serde_json::to_string(import)?,
name = serde_json::to_string(name)?,
key = StringifyJs(&shared.share_key),
version = StringifyJs(version),
import = StringifyJs(import),
name = StringifyJs(name),
eager = shared.eager,
));
}
let name_json = serde_json::to_string(name)?;
let source = format!(
r#"
const moduleMap = {{
......@@ -81,6 +81,7 @@ export {{ get, init }};
"#,
module_entries = module_entries.join(",\n "),
registrations = registrations.join("\n"),
name_json = StringifyJs(name),
);
Ok(ResolvedVc::upcast(
VirtualSource::new(
......
......@@ -15,6 +15,7 @@ use turbopack_core::{
},
virtual_source::VirtualSource,
};
use turbopack_ecmascript::utils::StringifyJs;
use crate::module_federation::config::{
ModuleFederationConfig, ModuleFederationRemote, ModuleFederationShared,
......@@ -36,10 +37,10 @@ fn provider_registrations(shared: &[ModuleFederationShared], host_name: &str) ->
eager: {eager}
}};"#,
index = registrations.len(),
key = serde_json::to_string(&shared.share_key)?,
version = serde_json::to_string(version)?,
import = serde_json::to_string(import)?,
host_name = serde_json::to_string(host_name)?,
key = StringifyJs(&shared.share_key),
version = StringifyJs(version),
import = StringifyJs(import),
host_name = StringifyJs(host_name),
eager = shared.eager,
));
}
......@@ -113,16 +114,12 @@ impl ImportMappingReplacement for ModuleFederationRemoteInitReplacer {
_request: Vc<Request>,
) -> Result<Vc<ImportMapResult>> {
let this = self.await?;
let candidates = serde_json::to_string(
&this
.remote
.external
.iter()
.map(|external| (&*external.global, &*external.url))
.collect::<Vec<_>>(),
)?;
let remote_key = serde_json::to_string(&this.remote.request)?;
let share_scope = serde_json::to_string(&this.remote.share_scope)?;
let candidates = this
.remote
.external
.iter()
.map(|external| (&*external.global, &*external.url))
.collect::<Vec<_>>();
let registrations = provider_registrations(&this.shared, &this.host_name)?;
let code = format!(
r#"
......@@ -193,6 +190,9 @@ export async function get(request, fullRequest) {{
throw error;
}}
"#,
candidates = StringifyJs(&candidates),
remote_key = StringifyJs(&this.remote.request),
share_scope = StringifyJs(&this.remote.share_scope),
);
let virtual_name = format!(
".turbopack-module-federation-init-{}.js",
......@@ -236,16 +236,16 @@ impl ImportMappingReplacement for ModuleFederationRemoteReplacer {
return Ok(ImportMapResult::NoEntry.cell());
};
let exposed_request_json = serde_json::to_string(&exposed_request)?;
let full_request = serde_json::to_string(&request)?;
let init_request = serde_json::to_string(&this.init_request)?;
let code = format!(
r#"
const {{ get }} = await import({init_request});
const factory = await get({exposed_request_json}, {full_request});
const federatedModule = factory();
__turbopack_export_namespace__(federatedModule);
"#
"#,
init_request = StringifyJs(&this.init_request),
exposed_request_json = StringifyJs(&exposed_request),
full_request = StringifyJs(&request),
);
let virtual_name = format!(
".turbopack-module-federation-remote-{}-{}.js",
......
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