Unverified Commit 69cbe4cb authored by Shu Ding's avatar Shu Ding Committed by GitHub

Optimize client entry creation (#51849)

Removed an unnecessary dependency mapping from the plugin.

Here's a quick visualization of this change. We have to traversal the module graph twice. The first iteration goes through all server modules and creates the client entries. And the second iteration collects info from all client modules.

Before this PR, the second iteration starts from server entries so it traversals both layers. With this PR, the second iteration will start from client entries only:

<img width="870" alt="CleanShot 2023-06-27 at 10 01 08@2x" src="https://github.com/vercel/next.js/assets/3676859/f0b7a0c6-0ade-483a-8645-48e2a8a6c9d0">

This is a ~100ms improvement for HMR of complicate apps.
parent aec75c2f
......@@ -53,7 +53,7 @@ import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin
import { regexLikeCss } from './webpack/config/blocks/css'
import { CopyFilePlugin } from './webpack/plugins/copy-file-plugin'
import { ClientReferenceManifestPlugin } from './webpack/plugins/flight-manifest-plugin'
import { ClientReferenceEntryPlugin } from './webpack/plugins/flight-client-entry-plugin'
import { FlightClientEntryPlugin } from './webpack/plugins/flight-client-entry-plugin'
import { NextTypesPlugin } from './webpack/plugins/next-types-plugin'
import type {
Feature,
......@@ -2420,7 +2420,7 @@ export default async function getBaseWebpackConfig(
dev,
appDir,
})
: new ClientReferenceEntryPlugin({
: new FlightClientEntryPlugin({
appDir,
dev,
isEdgeServer,
......
......@@ -6,7 +6,7 @@ import { getModuleBuildInfo } from '../get-module-build-info'
const noopHeadPath = require.resolve('next/dist/client/components/noop-head')
export default async function transformSource(
export default function transformSource(
this: any,
source: string,
sourceMap: any
......@@ -21,8 +21,6 @@ export default async function transformSource(
? 'next/dist/esm/build/webpack/loaders/next-flight-loader/module-proxy'
: 'next/dist/build/webpack/loaders/next-flight-loader/module-proxy'
const callback = this.async()
// Assign the RSC meta information to buildInfo.
// Exclude next internal files which are not marked as client files
const buildInfo = getModuleBuildInfo(this._module)
......@@ -55,11 +53,12 @@ export default async function transformSource(
if (assumedSourceType === 'module') {
if (clientRefs.includes('*')) {
return callback(
this.callback(
new Error(
`It's currently unsupported to use "export *" in a client boundary. Please use named exports instead.`
)
)
return
}
let esmSource = `\
......@@ -88,7 +87,8 @@ export { e${cnt++} as ${ref} };`
}
}
return callback(null, esmSource, sourceMap)
this.callback(null, esmSource, sourceMap)
return
}
}
......@@ -100,7 +100,7 @@ export { e${cnt++} as ${ref} };`
}
}
return callback(
this.callback(
null,
source.replace(RSC_MOD_REF_PROXY_ALIAS, moduleProxy),
sourceMap
......
......@@ -40,7 +40,7 @@ interface Options {
serverActionsBodySizeLimit?: SizeLimit
}
const PLUGIN_NAME = 'ClientEntryPlugin'
const PLUGIN_NAME = 'FlightClientEntryPlugin'
export type ActionManifest = {
[key in 'node' | 'edge']: {
......@@ -148,7 +148,7 @@ function deduplicateCSSImportsForEntry(mergedCSSimports: CssImports) {
return dedupedCSSImports
}
export class ClientReferenceEntryPlugin {
export class FlightClientEntryPlugin {
dev: boolean
appDir: string
isEdgeServer: boolean
......@@ -242,6 +242,10 @@ export class ClientReferenceEntryPlugin {
const addClientEntryAndSSRModulesList: Array<
ReturnType<typeof this.injectClientEntryAndSSRModules>
> = []
const createdSSRDependenciesForEntry: Record<
string,
ReturnType<typeof this.injectClientEntryAndSSRModules>[2][]
> = {}
const addActionEntryList: Array<ReturnType<typeof this.injectActionEntry>> =
[]
......@@ -265,7 +269,7 @@ export class ClientReferenceEntryPlugin {
const entryRequest = connection.dependency.request
const { clientComponentImports, actionImports, cssImports } =
this.collectComponentInfoFromDependencies({
this.collectComponentInfoFromServerEntryDependency({
entryRequest,
compilation,
dependency: entryDependency,
......@@ -315,16 +319,23 @@ export class ClientReferenceEntryPlugin {
// and SSR modules.
const dedupedCSSImports = deduplicateCSSImportsForEntry(mergedCSSimports)
for (const clientEntryToInject of clientEntriesToInject) {
addClientEntryAndSSRModulesList.push(
this.injectClientEntryAndSSRModules({
...clientEntryToInject,
clientImports: [
...clientEntryToInject.clientComponentImports,
...(dedupedCSSImports[clientEntryToInject.absolutePagePath] ||
[]),
],
})
const injected = this.injectClientEntryAndSSRModules({
...clientEntryToInject,
clientImports: [
...clientEntryToInject.clientComponentImports,
...(dedupedCSSImports[clientEntryToInject.absolutePagePath] || []),
],
})
// Track all created SSR dependencies for each entry from the server layer.
if (!createdSSRDependenciesForEntry[clientEntryToInject.entryName]) {
createdSSRDependenciesForEntry[clientEntryToInject.entryName] = []
}
createdSSRDependenciesForEntry[clientEntryToInject.entryName].push(
injected[2]
)
addClientEntryAndSSRModulesList.push(injected)
}
// Create internal app
......@@ -377,69 +388,22 @@ export class ClientReferenceEntryPlugin {
)
}
// To collect all CSS imports and action imports for a specific entry
// including the ones that are in the client graph, we need to store a
// map for client boundary dependencies.
function collectClientEntryDependencyMap(name: string) {
const clientEntryDependencyMap: Record<string, any> = {}
const entry = compilation.entries.get(name)
entry.includeDependencies.forEach((dep: any) => {
if (
dep.request &&
dep.request.startsWith('next-flight-client-entry-loader?')
) {
const mod: webpack.NormalModule =
compilation.moduleGraph.getResolvedModule(dep)
compilation.moduleGraph
.getOutgoingConnections(mod)
.forEach((connection: any) => {
if (connection.dependency) {
clientEntryDependencyMap[connection.dependency.request] =
connection.dependency
}
})
}
})
return clientEntryDependencyMap
}
// We need to create extra action entries that are created in the
// client layer.
compilation.hooks.finishModules.tapPromise(PLUGIN_NAME, () => {
const addedClientActionEntryList: Promise<any>[] = []
const actionMapsPerClientEntry: Record<string, Map<string, string[]>> = {}
forEachEntryModule(compilation, ({ name, entryModule }) => {
const actionEntryImports = new Map<string, string[]>()
const clientEntryDependencyMap = collectClientEntryDependencyMap(name)
const tracked = new Set<string>()
for (const connection of compilation.moduleGraph.getOutgoingConnections(
entryModule
)) {
const entryDependency = connection.dependency
const entryRequest = connection.dependency.request
// It is possible that the same entry is added multiple times in the
// connection graph. We can just skip these to speed up the process.
if (tracked.has(entryRequest)) continue
tracked.add(entryRequest)
const { clientActionImports } =
this.collectComponentInfoFromDependencies({
entryRequest,
compilation,
dependency: entryDependency,
clientEntryDependencyMap,
})
clientActionImports.forEach(([dep, names]) =>
actionEntryImports.set(dep, names)
)
}
// We need to create extra action entries that are created from the
// client layer.
// Start from each entry's created SSR dependency from our previous step.
for (const [name, ssrEntryDepdendencies] of Object.entries(
createdSSRDependenciesForEntry
)) {
// Collect from all entries, e.g. layout.js, page.js, loading.js, ...
// add agregate them.
const actionEntryImports = this.collectClientActionsFromDependencies({
compilation,
dependencies: ssrEntryDepdendencies,
})
if (actionEntryImports.size > 0) {
if (!this.useServerActions) {
......@@ -458,7 +422,7 @@ export class ClientReferenceEntryPlugin {
])
}
}
})
}
for (const [name, actionEntryImports] of Object.entries(
actionMapsPerClientEntry
......@@ -524,35 +488,106 @@ export class ClientReferenceEntryPlugin {
await Promise.all(addActionEntryList)
}
collectComponentInfoFromDependencies({
collectClientActionsFromDependencies({
compilation,
dependencies,
}: {
compilation: any
dependencies: ReturnType<typeof webpack.EntryPlugin.createDependency>[]
}) {
// action file path -> action names
const collectedActions = new Map<string, string[]>()
// Keep track of checked modules to avoid infinite loops with recursive imports.
const visitedModule = new Set<string>()
const visitedEntry = new Set<string>()
const collectActions = ({
entryRequest,
dependency,
}: {
entryRequest: string
dependency: any /* Dependency */
}) => {
const collectActionsInDep = (dependencyToFilter: any): void => {
const mod: webpack.NormalModule =
compilation.moduleGraph.getResolvedModule(dependencyToFilter)
if (!mod) return
// 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.
const modRequest: string | undefined =
mod.resourceResolveData?.path + mod.resourceResolveData?.query
if (!modRequest || visitedModule.has(modRequest)) return
visitedModule.add(modRequest)
const actions = getActions(mod)
if (actions) {
collectedActions.set(modRequest, actions)
}
compilation.moduleGraph
.getOutgoingConnections(mod)
.forEach((connection: any) => {
collectActionsInDep(connection.dependency)
})
}
// Don't traverse the module graph anymore once hitting the action layer.
if (!entryRequest.includes('next-flight-action-entry-loader')) {
// Traverse the module graph to find all client components.
collectActionsInDep(dependency)
}
}
for (const entryDependency of dependencies) {
const ssrEntryModule =
compilation.moduleGraph.getResolvedModule(entryDependency)
for (const connection of compilation.moduleGraph.getOutgoingConnections(
ssrEntryModule
)) {
const dependency = connection.dependency
const request = dependency.request
// It is possible that the same entry is added multiple times in the
// connection graph. We can just skip these to speed up the process.
if (visitedEntry.has(request)) continue
visitedEntry.add(request)
collectActions({
entryRequest: request,
dependency,
})
}
}
return collectedActions
}
collectComponentInfoFromServerEntryDependency({
entryRequest,
compilation,
dependency,
clientEntryDependencyMap,
}: {
entryRequest: string
compilation: any
dependency: any /* Dependency */
clientEntryDependencyMap?: Record<string, any>
}): {
cssImports: CssImports
clientComponentImports: ClientComponentImports
actionImports: [string, string[]][]
clientActionImports: [string, string[]][]
} {
/**
* Keep track of checked modules to avoid infinite loops with recursive imports.
*/
const visitedBySegment: { [segment: string]: Set<string> } = {}
// Keep track of checked modules to avoid infinite loops with recursive imports.
const visited = new Set()
// Info to collect.
const clientComponentImports: ClientComponentImports = []
const actionImports: [string, string[]][] = []
const clientActionImports: [string, string[]][] = []
const CSSImports = new Set<string>()
const filterClientComponents = (
dependencyToFilter: any,
inClientComponentBoundary: boolean
): void => {
const filterClientComponents = (dependencyToFilter: any): void => {
const mod: webpack.NormalModule =
compilation.moduleGraph.getResolvedModule(dependencyToFilter)
if (!mod) return
......@@ -565,26 +600,12 @@ export class ClientReferenceEntryPlugin {
const modRequest: string | undefined =
mod.resourceResolveData?.path + mod.resourceResolveData?.query
// Ensure module is not walked again if it's already been visited
if (!visitedBySegment[entryRequest]) {
visitedBySegment[entryRequest] = new Set()
}
const storeKey =
(inClientComponentBoundary ? '0' : '1') + ':' + modRequest
if (!modRequest || visitedBySegment[entryRequest].has(storeKey)) {
return
}
visitedBySegment[entryRequest].add(storeKey)
const isClientComponent = isClientComponentEntryModule(mod)
if (!modRequest || visited.has(modRequest)) return
visited.add(modRequest)
const actions = getActions(mod)
if (actions) {
if (isClientComponent) {
clientActionImports.push([modRequest, actions])
} else {
actionImports.push([modRequest, actions])
}
actionImports.push([modRequest, actions])
}
if (isCSS) {
......@@ -598,43 +619,26 @@ export class ClientReferenceEntryPlugin {
this.isEdgeServer ? EDGE_RUNTIME_WEBPACK : 'webpack-runtime'
)
if (unused) {
return
}
if (unused) return
}
CSSImports.add(modRequest)
}
if (!inClientComponentBoundary && isClientComponent) {
if (isClientComponentEntryModule(mod)) {
clientComponentImports.push(modRequest)
// Here we are entering a client boundary, and we need to collect dependencies
// in the client graph too.
if (clientEntryDependencyMap) {
if (clientEntryDependencyMap[modRequest]) {
filterClientComponents(clientEntryDependencyMap[modRequest], true)
}
}
return
}
compilation.moduleGraph
.getOutgoingConnections(mod)
.forEach((connection: any) => {
filterClientComponents(
connection.dependency,
inClientComponentBoundary || isClientComponent
)
filterClientComponents(connection.dependency)
})
}
// Don't traverse the module graph for the action loader.
if (!/next-flight-action-entry-loader/.test(entryRequest)) {
// Traverse the module graph to find all client components.
filterClientComponents(dependency, false)
}
// Traverse the module graph to find all client components.
filterClientComponents(dependency)
return {
clientComponentImports,
......@@ -644,7 +648,6 @@ export class ClientReferenceEntryPlugin {
}
: {},
actionImports,
clientActionImports,
}
}
......@@ -662,7 +665,11 @@ export class ClientReferenceEntryPlugin {
clientImports: ClientComponentImports
bundlePath: string
absolutePagePath?: string
}): [shouldInvalidate: boolean, addEntryPromise: Promise<void>] {
}): [
shouldInvalidate: boolean,
addEntryPromise: Promise<void>,
ssrDep: ReturnType<typeof webpack.EntryPlugin.createDependency>
] {
let shouldInvalidate = false
const loaderOptions: NextFlightClientEntryLoaderOptions = {
......@@ -750,6 +757,7 @@ export class ClientReferenceEntryPlugin {
layer: WEBPACK_LAYERS.client,
}
),
clientComponentEntryDep,
]
}
......@@ -843,50 +851,53 @@ export class ClientReferenceEntryPlugin {
compilation: webpack.Compilation,
assets: webpack.Compilation['assets']
) {
traverseModules(compilation, (mod, _chunk, chunkGroup, modId) => {
// Go through all action entries and record the module ID for each entry.
if (
chunkGroup.name &&
mod.request &&
/next-flight-action-entry-loader/.test(mod.request)
) {
const fromClient = /&__client_imported__=true/.test(mod.request)
const mapping = this.isEdgeServer
? pluginState.actionModEdgeServerId
: pluginState.actionModServerId
if (!mapping[chunkGroup.name]) {
mapping[chunkGroup.name] = {}
const serverActions: ActionManifest['node'] = {}
const edgeServerActions: ActionManifest['edge'] = {}
if (this.useServerActions) {
traverseModules(compilation, (mod, _chunk, chunkGroup, modId) => {
// Go through all action entries and record the module ID for each entry.
if (
chunkGroup.name &&
mod.request &&
/next-flight-action-entry-loader/.test(mod.request)
) {
const fromClient = /&__client_imported__=true/.test(mod.request)
const mapping = this.isEdgeServer
? pluginState.actionModEdgeServerId
: pluginState.actionModServerId
if (!mapping[chunkGroup.name]) {
mapping[chunkGroup.name] = {}
}
mapping[chunkGroup.name][fromClient ? 'client' : 'server'] = modId
}
mapping[chunkGroup.name][fromClient ? 'client' : 'server'] = modId
}
})
})
const serverActions: ActionManifest['node'] = {}
for (let id in pluginState.serverActions) {
const action = pluginState.serverActions[id]
for (let name in action.workers) {
const modId =
pluginState.actionModServerId[name][
action.layer[name] === WEBPACK_LAYERS.action ? 'client' : 'server'
]
action.workers[name] = modId!
for (let id in pluginState.serverActions) {
const action = pluginState.serverActions[id]
for (let name in action.workers) {
const modId =
pluginState.actionModServerId[name][
action.layer[name] === WEBPACK_LAYERS.action ? 'client' : 'server'
]
action.workers[name] = modId!
}
serverActions[id] = action
}
serverActions[id] = action
}
const edgeServerActions: ActionManifest['edge'] = {}
for (let id in pluginState.edgeServerActions) {
const action = pluginState.edgeServerActions[id]
for (let name in action.workers) {
const modId =
pluginState.actionModEdgeServerId[name][
action.layer[name] === WEBPACK_LAYERS.action ? 'client' : 'server'
]
action.workers[name] = modId!
for (let id in pluginState.edgeServerActions) {
const action = pluginState.edgeServerActions[id]
for (let name in action.workers) {
const modId =
pluginState.actionModEdgeServerId[name][
action.layer[name] === WEBPACK_LAYERS.action ? 'client' : 'server'
]
action.workers[name] = modId!
}
edgeServerActions[id] = action
}
edgeServerActions[id] = action
}
const json = JSON.stringify(
......
......@@ -98,20 +98,17 @@ export class ClientReferenceManifestPlugin {
webpack.dependencies.ModuleDependency,
new webpack.dependencies.NullDependency.Template()
)
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
// Have to be in the optimize stage to run after updating the CSS
// asset hash via extract mini css plugin.
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
},
(assets) => this.createAsset(assets, compilation, compiler.context)
)
}
)
compiler.hooks.make.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
// Have to be in the optimize stage to run after updating the CSS
// asset hash via extract mini css plugin.
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
},
(assets) => this.createAsset(assets, compilation, compiler.context)
)
})
}
createAsset(
......
......@@ -2,7 +2,7 @@ async function noopAction() {
'use server'
}
console.log(noopAction())
console.log(!!noopAction())
export default function Layout({ children }) {
return children
......
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