Unverified Commit 25be9caf authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix the plugin state for async modules in webpack plugins (#62998)

### What

Use the plugin state directly in flight plugins to access the async
modules collection

### Why

This change is cherry-picked from #62349 , where I found the plugin
state didn't store the async modules reousces properly due to the clone
of the array in flight manifest plugin. So for flight manifestp plugin
itself, it's holding a different instance rather than the one from proxy
state.

Closes NEXT-2743
parent ea5b23c8
......@@ -40,6 +40,7 @@ import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-s
import { getProxiedPluginState } from '../../build-context'
import { generateRandomActionKeyRaw } from '../../../server/app-render/action-encryption-utils'
import { PAGE_TYPES } from '../../../lib/page-types'
import { isWebpackServerOnlyLayer } from '../../utils'
interface Options {
dev: boolean
......@@ -95,7 +96,8 @@ const pluginState = getProxiedPluginState({
// Collect modules from server/edge compiler in client layer,
// and detect if it's been used, and mark it as `async: true` for react.
// So that react could unwrap the async module from promise and render module itself.
ASYNC_CLIENT_MODULES: [] as string[],
// Use an object to simulate Set lookup
ASYNC_CLIENT_MODULES: {} as Record<string, boolean>,
injectedClientEntries: {} as Record<string, string>,
})
......@@ -233,15 +235,15 @@ export class FlightClientEntryPlugin {
}
traverseModules(compilation, (mod, _chunk, _chunkGroup, modId) => {
// The module must has request, and resource so it's not a new entry created with loader.
// Using the client layer module, which doesn't have `rsc` tag in buildInfo.
if (mod.request && mod.resource && !mod.buildInfo.rsc) {
if (mod && mod.resource && !isWebpackServerOnlyLayer(mod.layer)) {
if (compilation.moduleGraph.isAsync(mod)) {
pluginState.ASYNC_CLIENT_MODULES.push(mod.resource)
// The module must has resolved resource path so it's not a new entry created with loader.
// Checking the module layer to make sure it's from client layers (SSR or browser, not RSC).
pluginState.ASYNC_CLIENT_MODULES[mod.resource] = true
}
}
recordModule(String(modId), mod)
if (modId) recordModule(modId, mod)
})
})
......@@ -539,11 +541,12 @@ export class FlightClientEntryPlugin {
const collectActionsInDep = (mod: webpack.NormalModule): void => {
if (!mod) return
const modPath: string = mod.resourceResolveData?.path || ''
// We have to always use the resolved request here to make sure the
// server and client are using the same module path (required by RSC), as
// the server compiler and client compiler have different resolve configs.
let modRequest: string | undefined =
mod.resourceResolveData?.path + mod.resourceResolveData?.query
let modRequest: string =
modPath + (mod.resourceResolveData?.query || '')
// For the barrel optimization, we need to use the match resource instead
// because there will be 2 modules for the same file (same resource path)
......@@ -633,11 +636,12 @@ export class FlightClientEntryPlugin {
const isCSS = isCSSMod(mod)
const modPath: string = mod.resourceResolveData?.path || ''
// We have to always use the resolved request here to make sure the
// server and client are using the same module path (required by RSC), as
// the server compiler and client compiler have different resolve configs.
let modRequest: string | undefined =
mod.resourceResolveData?.path + mod.resourceResolveData?.query
modPath + mod.resourceResolveData?.query
// Context modules don't have a resource path, we use the identifier instead.
if (mod.constructor.name === 'ContextModule') {
......@@ -945,6 +949,7 @@ export class FlightClientEntryPlugin {
if (
chunkGroup.name &&
mod.request &&
modId &&
/next-flight-action-entry-loader/.test(mod.request)
) {
const fromClient = /&__client_imported__=true/.test(mod.request)
......
......@@ -40,7 +40,8 @@ export type ManifestChunks = Array<string>
const pluginState = getProxiedPluginState({
serverModuleIds: {} as Record<string, string | number>,
edgeServerModuleIds: {} as Record<string, string | number>,
ASYNC_CLIENT_MODULES: [] as string[],
// Use an object to simulate Set lookup
ASYNC_CLIENT_MODULES: {} as Record<string, boolean>,
})
export interface ManifestNode {
......@@ -175,13 +176,11 @@ export class ClientReferenceManifestPlugin {
dev: Options['dev'] = false
appDir: Options['appDir']
appDirBase: string
ASYNC_CLIENT_MODULES: Set<string>
constructor(options: Options) {
this.dev = options.dev
this.appDir = options.appDir
this.appDirBase = path.dirname(this.appDir) + path.sep
this.ASYNC_CLIENT_MODULES = new Set(pluginState.ASYNC_CLIENT_MODULES)
}
apply(compiler: webpack.Compiler) {
......@@ -276,7 +275,7 @@ export class ClientReferenceManifestPlugin {
.filter((f) => !f.startsWith('static/css/pages/') && f.endsWith('.css'))
const requiredChunks = getAppPathRequiredChunks(entrypoint, rootMainFiles)
const recordModule = (id: ModuleId, mod: webpack.NormalModule) => {
const recordModule = (modId: ModuleId, mod: webpack.NormalModule) => {
let resource =
mod.type === 'css/mini-extract'
? // @ts-expect-error TODO: use `identifier()` instead.
......@@ -302,7 +301,7 @@ export class ClientReferenceManifestPlugin {
if (!ssrNamedModuleId.startsWith('.'))
ssrNamedModuleId = `./${ssrNamedModuleId.replace(/\\/g, '/')}`
const isAsyncModule = this.ASYNC_CLIENT_MODULES.has(mod.resource)
const isAsyncModule = !!pluginState.ASYNC_CLIENT_MODULES[mod.resource]
// The client compiler will always use the CJS Next.js build, so here we
// also add the mapping for the ESM build (Edge runtime) to consume.
......@@ -328,7 +327,7 @@ export class ClientReferenceManifestPlugin {
function addClientReference() {
const exportName = resource
manifest.clientModules[exportName] = {
id,
id: modId,
name: '*',
chunks: requiredChunks,
async: isAsyncModule,
......@@ -345,8 +344,8 @@ export class ClientReferenceManifestPlugin {
if (
typeof pluginState.serverModuleIds[ssrNamedModuleId] !== 'undefined'
) {
moduleIdMapping[id] = moduleIdMapping[id] || {}
moduleIdMapping[id]['*'] = {
moduleIdMapping[modId] = moduleIdMapping[modId] || {}
moduleIdMapping[modId]['*'] = {
...manifest.clientModules[exportName],
// During SSR, we don't have external chunks to load on the server
// side with our architecture of Webpack / Turbopack. We can keep
......@@ -360,8 +359,8 @@ export class ClientReferenceManifestPlugin {
typeof pluginState.edgeServerModuleIds[ssrNamedModuleId] !==
'undefined'
) {
edgeModuleIdMapping[id] = edgeModuleIdMapping[id] || {}
edgeModuleIdMapping[id]['*'] = {
edgeModuleIdMapping[modId] = edgeModuleIdMapping[modId] || {}
edgeModuleIdMapping[modId]['*'] = {
...manifest.clientModules[exportName],
// During SSR, we don't have external chunks to load on the server
// side with our architecture of Webpack / Turbopack. We can keep
......@@ -498,6 +497,6 @@ export class ClientReferenceManifestPlugin {
) as unknown as webpack.sources.RawSource
}
pluginState.ASYNC_CLIENT_MODULES = []
pluginState.ASYNC_CLIENT_MODULES = {}
}
}
......@@ -7,7 +7,7 @@ export function traverseModules(
mod: any,
chunk: webpack.Chunk,
chunkGroup: (typeof compilation.chunkGroups)[0],
modId: string | number
modId: string | null
) => any,
filterChunkGroup?: (chunkGroup: webpack.ChunkGroup) => boolean
) {
......@@ -21,7 +21,7 @@ export function traverseModules(
// TODO: Update type so that it doesn't have to be cast.
) as Iterable<webpack.NormalModule>
for (const mod of chunkModules) {
const modId = compilation.chunkGraph.getModuleId(mod)
const modId = compilation.chunkGraph.getModuleId(mod)?.toString()
callback(mod, chunk, chunkGroup, modId)
const anyModule = mod as any
if (anyModule.modules) {
......
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