Unverified Commit c376f391 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Use `registerClientReference` for ESM client component modules (#71968)

parent 0dffb14f
...@@ -88,7 +88,6 @@ import { ...@@ -88,7 +88,6 @@ import {
getBabelLoader, getBabelLoader,
getReactCompilerLoader, getReactCompilerLoader,
} from './get-babel-loader-config' } from './get-babel-loader-config'
import type { NextFlightLoaderOptions } from './webpack/loaders/next-flight-loader'
import { import {
NEXT_PROJECT_ROOT, NEXT_PROJECT_ROOT,
NEXT_PROJECT_ROOT_DIST_CLIENT, NEXT_PROJECT_ROOT_DIST_CLIENT,
...@@ -519,13 +518,6 @@ export default async function getBaseWebpackConfig( ...@@ -519,13 +518,6 @@ export default async function getBaseWebpackConfig(
babel: useSWCLoader ? swcDefaultLoader : babelLoader!, babel: useSWCLoader ? swcDefaultLoader : babelLoader!,
} }
const nextFlightLoader = {
loader: 'next-flight-loader',
options: {
isEdgeServer,
} satisfies NextFlightLoaderOptions,
}
const appServerLayerLoaders = hasAppDir const appServerLayerLoaders = hasAppDir
? [ ? [
// When using Babel, we will have to add the SWC loader // When using Babel, we will have to add the SWC loader
...@@ -539,7 +531,7 @@ export default async function getBaseWebpackConfig( ...@@ -539,7 +531,7 @@ export default async function getBaseWebpackConfig(
: [] : []
const instrumentLayerLoaders = [ const instrumentLayerLoaders = [
nextFlightLoader, 'next-flight-loader',
// When using Babel, we will have to add the SWC loader // When using Babel, we will have to add the SWC loader
// as an additional pass to handle RSC correctly. // as an additional pass to handle RSC correctly.
// This will cause some performance overhead but // This will cause some performance overhead but
...@@ -549,7 +541,7 @@ export default async function getBaseWebpackConfig( ...@@ -549,7 +541,7 @@ export default async function getBaseWebpackConfig(
].filter(Boolean) ].filter(Boolean)
const middlewareLayerLoaders = [ const middlewareLayerLoaders = [
nextFlightLoader, 'next-flight-loader',
// When using Babel, we will have to use SWC to do the optimization // When using Babel, we will have to use SWC to do the optimization
// for middleware to tree shake the unused default optimized imports like "next/server". // for middleware to tree shake the unused default optimized imports like "next/server".
// This will cause some performance overhead but // This will cause some performance overhead but
...@@ -1366,7 +1358,7 @@ export default async function getBaseWebpackConfig( ...@@ -1366,7 +1358,7 @@ export default async function getBaseWebpackConfig(
isEdgeServer, isEdgeServer,
}), }),
}, },
use: nextFlightLoader, use: 'next-flight-loader',
}, },
] ]
: []), : []),
......
...@@ -2,8 +2,6 @@ import type { webpack } from 'next/dist/compiled/webpack/webpack' ...@@ -2,8 +2,6 @@ import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { RSC_MOD_REF_PROXY_ALIAS } from '../../../../lib/constants' import { RSC_MOD_REF_PROXY_ALIAS } from '../../../../lib/constants'
import { import {
BARREL_OPTIMIZATION_PREFIX, BARREL_OPTIMIZATION_PREFIX,
DEFAULT_RUNTIME_WEBPACK,
EDGE_RUNTIME_WEBPACK,
RSC_MODULE_TYPES, RSC_MODULE_TYPES,
} from '../../../../shared/lib/constants' } from '../../../../shared/lib/constants'
import { warnOnce } from '../../../../shared/lib/utils/warn-once' import { warnOnce } from '../../../../shared/lib/utils/warn-once'
...@@ -14,11 +12,6 @@ import type { ...@@ -14,11 +12,6 @@ import type {
javascript, javascript,
LoaderContext, LoaderContext,
} from 'next/dist/compiled/webpack/webpack' } from 'next/dist/compiled/webpack/webpack'
import picomatch from 'next/dist/compiled/picomatch'
export interface NextFlightLoaderOptions {
isEdgeServer: boolean
}
type SourceType = javascript.JavascriptParser['sourceType'] | 'commonjs' type SourceType = javascript.JavascriptParser['sourceType'] | 'commonjs'
...@@ -27,10 +20,6 @@ const noopHeadPath = require.resolve('next/dist/client/components/noop-head') ...@@ -27,10 +20,6 @@ const noopHeadPath = require.resolve('next/dist/client/components/noop-head')
const MODULE_PROXY_PATH = const MODULE_PROXY_PATH =
'next/dist/build/webpack/loaders/next-flight-loader/module-proxy' 'next/dist/build/webpack/loaders/next-flight-loader/module-proxy'
const isSharedRuntime = picomatch('**/next/dist/**/*.shared-runtime.js', {
dot: true, // required for .pnpm paths
})
export function getAssumedSourceType( export function getAssumedSourceType(
mod: webpack.Module, mod: webpack.Module,
sourceType: SourceType sourceType: SourceType
...@@ -42,26 +31,31 @@ export function getAssumedSourceType( ...@@ -42,26 +31,31 @@ export function getAssumedSourceType(
// It's tricky to detect the type of a client boundary, but we should always // It's tricky to detect the type of a client boundary, but we should always
// use the `module` type when we can, to support `export *` and `export from` // use the `module` type when we can, to support `export *` and `export from`
// syntax in other modules that import this client boundary. // syntax in other modules that import this client boundary.
let assumedSourceType = sourceType
if (assumedSourceType === 'auto' && detectedClientEntryType === 'auto') { if (sourceType === 'auto') {
if ( if (detectedClientEntryType === 'auto') {
clientRefs.length === 0 || if (
(clientRefs.length === 1 && clientRefs[0] === '') clientRefs.length === 0 ||
) { (clientRefs.length === 1 && clientRefs[0] === '')
// If there's zero export detected in the client boundary, and it's the ) {
// `auto` type, we can safely assume it's a CJS module because it doesn't // If there's zero export detected in the client boundary, and it's the
// have ESM exports. // `auto` type, we can safely assume it's a CJS module because it doesn't
assumedSourceType = 'commonjs' // have ESM exports.
} else if (!clientRefs.includes('*')) { return 'commonjs'
// Otherwise, we assume it's an ESM module. } else if (!clientRefs.includes('*')) {
assumedSourceType = 'module' // Otherwise, we assume it's an ESM module.
return 'module'
}
} else if (detectedClientEntryType === 'cjs') {
return 'commonjs'
} }
} }
return assumedSourceType
return sourceType
} }
export default function transformSource( export default function transformSource(
this: LoaderContext<NextFlightLoaderOptions>, this: LoaderContext<undefined>,
source: string, source: string,
sourceMap: any sourceMap: any
) { ) {
...@@ -70,8 +64,6 @@ export default function transformSource( ...@@ -70,8 +64,6 @@ export default function transformSource(
throw new Error('Expected source to have been transformed to a string.') throw new Error('Expected source to have been transformed to a string.')
} }
const options = this.getOptions()
const { isEdgeServer } = options
const module = this._module! const module = this._module!
// Assign the RSC meta information to buildInfo. // Assign the RSC meta information to buildInfo.
...@@ -107,6 +99,7 @@ export default function transformSource( ...@@ -107,6 +99,7 @@ export default function transformSource(
) )
const clientRefs = buildInfo.rsc.clientRefs! const clientRefs = buildInfo.rsc.clientRefs!
const stringifiedResourceKey = JSON.stringify(resourceKey)
if (assumedSourceType === 'module') { if (assumedSourceType === 'module') {
if (clientRefs.includes('*')) { if (clientRefs.includes('*')) {
...@@ -118,46 +111,40 @@ export default function transformSource( ...@@ -118,46 +111,40 @@ export default function transformSource(
return return
} }
if (!isSharedRuntime(resourceKey)) {
// Prevent module concatenation, and prevent export names from being
// mangled, in production builds, so that exports of client reference
// modules can be resolved by React using the metadata from the client
// manifest.
this._compilation!.moduleGraph.getExportsInfo(
module
).setUsedInUnknownWay(
isEdgeServer ? EDGE_RUNTIME_WEBPACK : DEFAULT_RUNTIME_WEBPACK
)
}
// `proxy` is the module proxy that we treat the module as a client boundary.
// For ESM, we access the property of the module proxy directly for each export.
// This is bit hacky that treating using a CJS like module proxy for ESM's exports,
// but this will avoid creating nested proxies for each export. It will be improved in the future.
// Explanation for: await createProxy(...)
// We need to await the module proxy creation because it can be async module for SSR layer
// due to having async dependencies.
// We only apply `the await` for Node.js as only Edge doesn't have external dependencies.
let esmSource = `\ let esmSource = `\
import { createProxy } from "${MODULE_PROXY_PATH}" import { registerClientReference } from "react-server-dom-webpack/server.edge";
const proxy = ${isEdgeServer ? '' : 'await'} createProxy(String.raw\`${resourceKey}\`)
` `
let cnt = 0
for (const ref of clientRefs) { for (const ref of clientRefs) {
if (ref === '') { if (ref === 'default') {
esmSource += `exports[''] = proxy['']\n` esmSource += `export default registerClientReference(
} else if (ref === 'default') { function() { throw new Error(${JSON.stringify(`Attempted to call the default \
esmSource += `export default proxy.default;\n` export of ${stringifiedResourceKey} from the server, but it's on the client. \
It's not possible to invoke a client function from the server, it can only be \
rendered as a Component or passed to props of a Client Component.`)}); },
${stringifiedResourceKey},
"default",
);\n`
} else { } else {
esmSource += `const e${cnt} = proxy["${ref}"];\n` esmSource += `export const ${ref} = registerClientReference(
esmSource += `export { e${cnt++} as ${ref} };\n` function() { throw new Error(${JSON.stringify(`Attempted to call ${ref}() from \
the server but ${ref} is on the client. It's not possible to invoke a client \
function from the server, it can only be rendered as a Component or passed to \
props of a Client Component.`)}); },
${stringifiedResourceKey},
${JSON.stringify(ref)},
);`
} }
} }
this.callback(null, esmSource, sourceMap) return this.callback(null, esmSource, sourceMap)
return } else if (assumedSourceType === 'commonjs') {
let cjsSource = `\
const { createProxy } = require("${MODULE_PROXY_PATH}")
module.exports = createProxy(${stringifiedResourceKey})
`
return this.callback(null, cjsSource, sourceMap)
} }
} }
......
...@@ -72,32 +72,29 @@ export type ActionManifest = { ...@@ -72,32 +72,29 @@ export type ActionManifest = {
edge: Actions edge: Actions
} }
export interface ModuleInfo {
moduleId: string | number
async: boolean
}
const pluginState = getProxiedPluginState({ const pluginState = getProxiedPluginState({
// A map to track "action" -> "list of bundles". // A map to track "action" -> "list of bundles".
serverActions: {} as ActionManifest['node'], serverActions: {} as ActionManifest['node'],
edgeServerActions: {} as ActionManifest['edge'], edgeServerActions: {} as ActionManifest['edge'],
actionModServerId: {} as Record< serverActionModules: {} as {
string, [workerName: string]: { server?: ModuleInfo; client?: ModuleInfo }
{ },
server?: { moduleId: string | number; async: boolean }
client?: { moduleId: string | number; async: boolean } edgeServerActionModules: {} as {
} [workerName: string]: { server?: ModuleInfo; client?: ModuleInfo }
>, },
actionModEdgeServerId: {} as Record<
string,
{
server?: { moduleId: string | number; async: boolean }
client?: { moduleId: string | number; async: boolean }
}
>,
// Mapping of resource path to module id for server/edge server. ssrModules: {} as { [ssrModuleId: string]: ModuleInfo },
serverModuleIds: {} as Record<string, string | number>, edgeSsrModules: {} as { [ssrModuleId: string]: ModuleInfo },
edgeServerModuleIds: {} as Record<string, string | number>,
rscModuleIds: {} as Record<string, string | number>, rscModules: {} as { [rscModuleId: string]: ModuleInfo },
edgeRscModuleIds: {} as Record<string, string | number>, edgeRscModules: {} as { [rscModuleId: string]: ModuleInfo },
injectedClientEntries: {} as Record<string, string>, injectedClientEntries: {} as Record<string, string>,
}) })
...@@ -220,10 +217,15 @@ export class FlightClientEntryPlugin { ...@@ -220,10 +217,15 @@ export class FlightClientEntryPlugin {
.relative(compiler.context, modResource) .relative(compiler.context, modResource)
.replace(/\/next\/dist\/esm\//, '/next/dist/') .replace(/\/next\/dist\/esm\//, '/next/dist/')
const moduleInfo: ModuleInfo = {
moduleId: modId,
async: compilation.moduleGraph.isAsync(mod),
}
if (this.isEdgeServer) { if (this.isEdgeServer) {
pluginState.edgeRscModuleIds[key] = modId pluginState.edgeRscModules[key] = moduleInfo
} else { } else {
pluginState.rscModuleIds[key] = modId pluginState.rscModules[key] = moduleInfo
} }
} }
} }
...@@ -244,12 +246,17 @@ export class FlightClientEntryPlugin { ...@@ -244,12 +246,17 @@ export class FlightClientEntryPlugin {
ssrNamedModuleId = `./${normalizePathSep(ssrNamedModuleId)}` ssrNamedModuleId = `./${normalizePathSep(ssrNamedModuleId)}`
} }
const moduleInfo: ModuleInfo = {
moduleId: modId,
async: compilation.moduleGraph.isAsync(mod),
}
if (this.isEdgeServer) { if (this.isEdgeServer) {
pluginState.edgeServerModuleIds[ pluginState.edgeSsrModules[
ssrNamedModuleId.replace(/\/next\/dist\/esm\//, '/next/dist/') ssrNamedModuleId.replace(/\/next\/dist\/esm\//, '/next/dist/')
] = modId ] = moduleInfo
} else { } else {
pluginState.serverModuleIds[ssrNamedModuleId] = modId pluginState.ssrModules[ssrNamedModuleId] = moduleInfo
} }
} }
} }
...@@ -279,7 +286,7 @@ export class FlightClientEntryPlugin { ...@@ -279,7 +286,7 @@ export class FlightClientEntryPlugin {
> = [] > = []
const createdSSRDependenciesForEntry: Record< const createdSSRDependenciesForEntry: Record<
string, string,
ReturnType<typeof this.injectClientEntryAndSSRModules>[2][] ReturnType<typeof this.injectClientEntryAndSSRModules>[3][]
> = {} > = {}
const addActionEntryList: Array<ReturnType<typeof this.injectActionEntry>> = const addActionEntryList: Array<ReturnType<typeof this.injectActionEntry>> =
...@@ -393,7 +400,7 @@ export class FlightClientEntryPlugin { ...@@ -393,7 +400,7 @@ export class FlightClientEntryPlugin {
createdSSRDependenciesForEntry[clientEntryToInject.entryName] = [] createdSSRDependenciesForEntry[clientEntryToInject.entryName] = []
} }
createdSSRDependenciesForEntry[clientEntryToInject.entryName].push( createdSSRDependenciesForEntry[clientEntryToInject.entryName].push(
injected[2] injected[3]
) )
addClientEntryAndSSRModulesList.push(injected) addClientEntryAndSSRModulesList.push(injected)
...@@ -450,12 +457,14 @@ export class FlightClientEntryPlugin { ...@@ -450,12 +457,14 @@ export class FlightClientEntryPlugin {
invalidator.invalidate([COMPILER_NAMES.client]) invalidator.invalidate([COMPILER_NAMES.client])
} }
// Client compiler is invalidated before awaiting the compilation of the SSR client component entries // Client compiler is invalidated before awaiting the compilation of the SSR
// so that the client compiler is running in parallel to the server compiler. // and RSC client component entries so that the client compiler is running
// in parallel to the server compiler.
await Promise.all( await Promise.all(
addClientEntryAndSSRModulesList.map( addClientEntryAndSSRModulesList.flatMap((addClientEntryAndSSRModules) => [
(addClientEntryAndSSRModules) => addClientEntryAndSSRModules[1] addClientEntryAndSSRModules[1],
) addClientEntryAndSSRModules[2],
])
) )
// Wait for action entries to be added. // Wait for action entries to be added.
...@@ -737,7 +746,8 @@ export class FlightClientEntryPlugin { ...@@ -737,7 +746,8 @@ export class FlightClientEntryPlugin {
absolutePagePath?: string absolutePagePath?: string
}): [ }): [
shouldInvalidate: boolean, shouldInvalidate: boolean,
addEntryPromise: Promise<void>, addSSREntryPromise: Promise<void>,
addRSCEntryPromise: Promise<void>,
ssrDep: ReturnType<typeof webpack.EntryPlugin.createDependency>, ssrDep: ReturnType<typeof webpack.EntryPlugin.createDependency>,
] { ] {
let shouldInvalidate = false let shouldInvalidate = false
...@@ -766,7 +776,7 @@ export class FlightClientEntryPlugin { ...@@ -766,7 +776,7 @@ export class FlightClientEntryPlugin {
server: false, server: false,
})}!` })}!`
const clientSSRLoader = `next-flight-client-entry-loader?${stringify({ const clientServerLoader = `next-flight-client-entry-loader?${stringify({
modules: modules.map((x) => JSON.stringify(x)), modules: modules.map((x) => JSON.stringify(x)),
server: true, server: true,
})}!` })}!`
...@@ -809,33 +819,30 @@ export class FlightClientEntryPlugin { ...@@ -809,33 +819,30 @@ export class FlightClientEntryPlugin {
pluginState.injectedClientEntries[bundlePath] = clientBrowserLoader pluginState.injectedClientEntries[bundlePath] = clientBrowserLoader
} }
// Inject the entry to the server compiler (__ssr__). const clientComponentSSREntryDep = webpack.EntryPlugin.createDependency(
const clientComponentEntryDep = webpack.EntryPlugin.createDependency( clientServerLoader,
clientSSRLoader, { name: bundlePath }
{ )
name: bundlePath,
} const clientComponentRSCEntryDep = webpack.EntryPlugin.createDependency(
clientServerLoader,
{ name: bundlePath }
) )
return [ return [
shouldInvalidate, shouldInvalidate,
// Add the dependency to the server compiler. // Add the entries to the server compiler for the SSR and RSC layers. The
// This promise is awaited later using `Promise.all` in order to parallelize adding the entries. // promises are awaited later using `Promise.all` in order to parallelize
// It ensures we can parallelize the SSR and Client compiler entries. // adding the entries.
this.addEntry( this.addEntry(compilation, compiler.context, clientComponentSSREntryDep, {
compilation, name: entryName,
// Reuse compilation context. layer: WEBPACK_LAYERS.serverSideRendering,
compiler.context, }),
clientComponentEntryDep, this.addEntry(compilation, compiler.context, clientComponentRSCEntryDep, {
{ name: entryName,
// By using the same entry name layer: WEBPACK_LAYERS.reactServerComponents,
name: entryName, }),
// Layer should be client for the SSR modules clientComponentSSREntryDep,
// This ensures the client components are bundled on client layer
layer: WEBPACK_LAYERS.serverSideRendering,
}
),
clientComponentEntryDep,
] ]
} }
...@@ -968,8 +975,8 @@ export class FlightClientEntryPlugin { ...@@ -968,8 +975,8 @@ export class FlightClientEntryPlugin {
const fromClient = /&__client_imported__=true/.test(mod.request) const fromClient = /&__client_imported__=true/.test(mod.request)
const mapping = this.isEdgeServer const mapping = this.isEdgeServer
? pluginState.actionModEdgeServerId ? pluginState.edgeServerActionModules
: pluginState.actionModServerId : pluginState.serverActionModules
if (!mapping[chunkGroup.name]) { if (!mapping[chunkGroup.name]) {
mapping[chunkGroup.name] = {} mapping[chunkGroup.name] = {}
...@@ -985,7 +992,7 @@ export class FlightClientEntryPlugin { ...@@ -985,7 +992,7 @@ export class FlightClientEntryPlugin {
const action = pluginState.serverActions[id] const action = pluginState.serverActions[id]
for (let name in action.workers) { for (let name in action.workers) {
const modId = const modId =
pluginState.actionModServerId[name][ pluginState.serverActionModules[name][
action.layer[name] === WEBPACK_LAYERS.actionBrowser action.layer[name] === WEBPACK_LAYERS.actionBrowser
? 'client' ? 'client'
: 'server' : 'server'
...@@ -999,7 +1006,7 @@ export class FlightClientEntryPlugin { ...@@ -999,7 +1006,7 @@ export class FlightClientEntryPlugin {
const action = pluginState.edgeServerActions[id] const action = pluginState.edgeServerActions[id]
for (let name in action.workers) { for (let name in action.workers) {
const modId = const modId =
pluginState.actionModEdgeServerId[name][ pluginState.edgeServerActionModules[name][
action.layer[name] === WEBPACK_LAYERS.actionBrowser action.layer[name] === WEBPACK_LAYERS.actionBrowser
? 'client' ? 'client'
: 'server' : 'server'
......
...@@ -27,6 +27,7 @@ import { ...@@ -27,6 +27,7 @@ import {
import type { ChunkGroup } from 'webpack' import type { ChunkGroup } from 'webpack'
import { encodeURIPath } from '../../../shared/lib/encode-uri-path' import { encodeURIPath } from '../../../shared/lib/encode-uri-path'
import { isMetadataRoute } from '../../../lib/metadata/is-metadata-route' import { isMetadataRoute } from '../../../lib/metadata/is-metadata-route'
import type { ModuleInfo } from './flight-client-entry-plugin'
interface Options { interface Options {
dev: boolean dev: boolean
...@@ -43,11 +44,11 @@ type ModuleId = string | number /*| null*/ ...@@ -43,11 +44,11 @@ type ModuleId = string | number /*| null*/
export type ManifestChunks = Array<string> export type ManifestChunks = Array<string>
const pluginState = getProxiedPluginState({ const pluginState = getProxiedPluginState({
serverModuleIds: {} as Record<string, string | number>, ssrModules: {} as { [ssrModuleId: string]: ModuleInfo },
edgeServerModuleIds: {} as Record<string, string | number>, edgeSsrModules: {} as { [ssrModuleId: string]: ModuleInfo },
rscModuleIds: {} as Record<string, string | number>, rscModules: {} as { [rscModuleId: string]: ModuleInfo },
edgeRscModuleIds: {} as Record<string, string | number>, edgeRscModules: {} as { [rscModuleId: string]: ModuleInfo },
}) })
export interface ManifestNode { export interface ManifestNode {
...@@ -356,12 +357,18 @@ export class ClientReferenceManifestPlugin { ...@@ -356,12 +357,18 @@ export class ClientReferenceManifestPlugin {
} }
function addClientReference() { function addClientReference() {
const isAsync = Boolean(
compilation.moduleGraph.isAsync(mod) ||
pluginState.ssrModules[ssrNamedModuleId]?.async ||
pluginState.edgeSsrModules[ssrNamedModuleId]?.async
)
const exportName = resource const exportName = resource
manifest.clientModules[exportName] = { manifest.clientModules[exportName] = {
id: modId, id: modId,
name: '*', name: '*',
chunks: requiredChunks, chunks: requiredChunks,
async: false, async: isAsync,
} }
if (esmResource) { if (esmResource) {
const edgeExportName = esmResource const edgeExportName = esmResource
...@@ -372,9 +379,9 @@ export class ClientReferenceManifestPlugin { ...@@ -372,9 +379,9 @@ export class ClientReferenceManifestPlugin {
function addSSRIdMapping() { function addSSRIdMapping() {
const exportName = resource const exportName = resource
if ( const moduleInfo = pluginState.ssrModules[ssrNamedModuleId]
typeof pluginState.serverModuleIds[ssrNamedModuleId] !== 'undefined'
) { if (moduleInfo) {
moduleIdMapping[modId] = moduleIdMapping[modId] || {} moduleIdMapping[modId] = moduleIdMapping[modId] || {}
moduleIdMapping[modId]['*'] = { moduleIdMapping[modId]['*'] = {
...manifest.clientModules[exportName], ...manifest.clientModules[exportName],
...@@ -382,14 +389,14 @@ export class ClientReferenceManifestPlugin { ...@@ -382,14 +389,14 @@ export class ClientReferenceManifestPlugin {
// side with our architecture of Webpack / Turbopack. We can keep // side with our architecture of Webpack / Turbopack. We can keep
// this field empty to save some bytes. // this field empty to save some bytes.
chunks: [], chunks: [],
id: pluginState.serverModuleIds[ssrNamedModuleId], id: moduleInfo.moduleId,
async: moduleInfo.async,
} }
} }
if ( const edgeModuleInfo = pluginState.edgeSsrModules[ssrNamedModuleId]
typeof pluginState.edgeServerModuleIds[ssrNamedModuleId] !==
'undefined' if (edgeModuleInfo) {
) {
edgeModuleIdMapping[modId] = edgeModuleIdMapping[modId] || {} edgeModuleIdMapping[modId] = edgeModuleIdMapping[modId] || {}
edgeModuleIdMapping[modId]['*'] = { edgeModuleIdMapping[modId]['*'] = {
...manifest.clientModules[exportName], ...manifest.clientModules[exportName],
...@@ -397,16 +404,17 @@ export class ClientReferenceManifestPlugin { ...@@ -397,16 +404,17 @@ export class ClientReferenceManifestPlugin {
// side with our architecture of Webpack / Turbopack. We can keep // side with our architecture of Webpack / Turbopack. We can keep
// this field empty to save some bytes. // this field empty to save some bytes.
chunks: [], chunks: [],
id: pluginState.edgeServerModuleIds[ssrNamedModuleId], id: edgeModuleInfo.moduleId,
async: edgeModuleInfo.async,
} }
} }
} }
function addRSCIdMapping() { function addRSCIdMapping() {
const exportName = resource const exportName = resource
if ( const moduleInfo = pluginState.rscModules[rscNamedModuleId]
typeof pluginState.rscModuleIds[rscNamedModuleId] !== 'undefined'
) { if (moduleInfo) {
rscIdMapping[modId] = rscIdMapping[modId] || {} rscIdMapping[modId] = rscIdMapping[modId] || {}
rscIdMapping[modId]['*'] = { rscIdMapping[modId]['*'] = {
...manifest.clientModules[exportName], ...manifest.clientModules[exportName],
...@@ -414,14 +422,14 @@ export class ClientReferenceManifestPlugin { ...@@ -414,14 +422,14 @@ export class ClientReferenceManifestPlugin {
// side with our architecture of Webpack / Turbopack. We can keep // side with our architecture of Webpack / Turbopack. We can keep
// this field empty to save some bytes. // this field empty to save some bytes.
chunks: [], chunks: [],
id: pluginState.rscModuleIds[rscNamedModuleId], id: moduleInfo.moduleId,
async: moduleInfo.async,
} }
} }
if ( const edgeModuleInfo = pluginState.ssrModules[rscNamedModuleId]
typeof pluginState.edgeRscModuleIds[rscNamedModuleId] !==
'undefined' if (edgeModuleInfo) {
) {
edgeRscIdMapping[modId] = edgeRscIdMapping[modId] || {} edgeRscIdMapping[modId] = edgeRscIdMapping[modId] || {}
edgeRscIdMapping[modId]['*'] = { edgeRscIdMapping[modId]['*'] = {
...manifest.clientModules[exportName], ...manifest.clientModules[exportName],
...@@ -429,7 +437,8 @@ export class ClientReferenceManifestPlugin { ...@@ -429,7 +437,8 @@ export class ClientReferenceManifestPlugin {
// side with our architecture of Webpack / Turbopack. We can keep // side with our architecture of Webpack / Turbopack. We can keep
// this field empty to save some bytes. // this field empty to save some bytes.
chunks: [], chunks: [],
id: pluginState.edgeRscModuleIds[rscNamedModuleId], id: edgeModuleInfo.moduleId,
async: edgeModuleInfo.async,
} }
} }
} }
......
...@@ -24,6 +24,7 @@ import { getPageFilePath } from '../../entries' ...@@ -24,6 +24,7 @@ import { getPageFilePath } from '../../entries'
import { resolveExternal } from '../../handle-externals' import { resolveExternal } from '../../handle-externals'
import swcLoader from '../loaders/next-swc-loader' import swcLoader from '../loaders/next-swc-loader'
import { isMetadataRoute } from '../../../lib/metadata/is-metadata-route' import { isMetadataRoute } from '../../../lib/metadata/is-metadata-route'
import { isClientComponentEntryModule } from '../loaders/utils'
const PLUGIN_NAME = 'TraceEntryPointsPlugin' const PLUGIN_NAME = 'TraceEntryPointsPlugin'
export const TRACE_IGNORES = [ export const TRACE_IGNORES = [
...@@ -533,10 +534,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance { ...@@ -533,10 +534,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
// fallback to reading raw source file, this may fail // fallback to reading raw source file, this may fail
// due to unsupported syntax but best effort attempt // due to unsupported syntax but best effort attempt
let usingOriginalSource = false let usingOriginalSource = false
if ( if (!source || isClientComponentEntryModule(mod)) {
!source ||
source.toString().includes('next-flight-loader/module-proxy')
) {
source = await readOriginalSource(path) source = await readOriginalSource(path)
usingOriginalSource = true usingOriginalSource = true
} }
......
'use client'
export function Button() {
return <button>submit</button>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
// x-ref: https://github.com/vercel/next.js/issues/71840
import { ElementType } from 'react'
async function getImport(
slug: string,
exportName: string
): Promise<ElementType> {
const moduleExports = await import(`./${slug}`)
return moduleExports[exportName]
}
export default async function Home() {
const Button = await getImport('button', 'Button')
return <Button />
}
import { nextTestSetup } from 'e2e-utils'
describe('dynamic-import', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should render the dynamically imported component', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('button').text()).toBe('submit')
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic' ...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic'
const Button = dynamic(() => const Button = dynamic(() =>
import('./client').then((mod) => { import('./client').then((mod) => {
return { default: mod.Button } return mod.Button
}) })
) )
......
...@@ -231,8 +231,7 @@ describe('app dir - rsc basics', () => { ...@@ -231,8 +231,7 @@ describe('app dir - rsc basics', () => {
expect(html).toContain('dynamic data!') expect(html).toContain('dynamic data!')
}) })
// TODO: TLA in client references are currently broken with Webpack on Edge describe.each(['node', 'edge'])(
describe.each(process.env.TURBOPACK ? ['node', 'edge'] : ['node'])(
'client references with TLA (%s)', 'client references with TLA (%s)',
(runtime) => { (runtime) => {
let url = `/async-client${runtime === 'edge' ? '/edge' : ''}` let url = `/async-client${runtime === 'edge' ? '/edge' : ''}`
......
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