Unverified Commit fdc071c5 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Move FlightManifestPlugin to server compilers (#36810)

* move FlightManifestPlugin to server compilers

* revert loader condition

* fix module id

* fix test and refactor
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 22c0b65e
...@@ -909,9 +909,8 @@ export default async function getBaseWebpackConfig( ...@@ -909,9 +909,8 @@ export default async function getBaseWebpackConfig(
}, },
} }
const rscCodeCondition = { const serverComponentCodeCondition = {
test: serverComponentsRegex, test: serverComponentsRegex,
// only apply to the pages as the begin process of rsc loaders
include: [dir, /next[\\/]dist[\\/]pages/], include: [dir, /next[\\/]dist[\\/]pages/],
} }
...@@ -1210,7 +1209,7 @@ export default async function getBaseWebpackConfig( ...@@ -1210,7 +1209,7 @@ export default async function getBaseWebpackConfig(
? [ ? [
// RSC server compilation loaders // RSC server compilation loaders
{ {
...rscCodeCondition, ...serverComponentCodeCondition,
use: { use: {
loader: 'next-flight-server-loader', loader: 'next-flight-server-loader',
}, },
...@@ -1219,7 +1218,7 @@ export default async function getBaseWebpackConfig( ...@@ -1219,7 +1218,7 @@ export default async function getBaseWebpackConfig(
: [ : [
// RSC client compilation loaders // RSC client compilation loaders
{ {
...rscCodeCondition, ...serverComponentCodeCondition,
use: { use: {
loader: 'next-flight-server-loader', loader: 'next-flight-server-loader',
options: { options: {
...@@ -1589,8 +1588,12 @@ export default async function getBaseWebpackConfig( ...@@ -1589,8 +1588,12 @@ export default async function getBaseWebpackConfig(
}, },
}), }),
hasServerComponents && hasServerComponents &&
isClient && !isClient &&
new FlightManifestPlugin({ dev, pageExtensions: rawPageExtensions }), new FlightManifestPlugin({
dev,
pageExtensions: rawPageExtensions,
isEdgeServer,
}),
!dev && !dev &&
isClient && isClient &&
new TelemetryPlugin( new TelemetryPlugin(
......
...@@ -3,8 +3,8 @@ import { builtinModules } from 'module' ...@@ -3,8 +3,8 @@ import { builtinModules } from 'module'
import { parse } from '../../swc' import { parse } from '../../swc'
import { import {
buildExports, buildExports,
createClientComponentFilter, clientComponentRegex,
createServerComponentFilter, serverComponentRegex,
isNextBuiltinClientComponent, isNextBuiltinClientComponent,
} from './utils' } from './utils'
...@@ -25,15 +25,11 @@ async function parseModuleInfo({ ...@@ -25,15 +25,11 @@ async function parseModuleInfo({
resourcePath, resourcePath,
source, source,
isClientCompilation, isClientCompilation,
isServerComponent,
isClientComponent,
resolver, resolver,
}: { }: {
resourcePath: string resourcePath: string
source: string source: string
isClientCompilation: boolean isClientCompilation: boolean
isServerComponent: (name: string) => boolean
isClientComponent: (name: string) => boolean
resolver: (req: string) => Promise<string> resolver: (req: string) => Promise<string>
}): Promise<{ }): Promise<{
source: string source: string
...@@ -71,10 +67,10 @@ async function parseModuleInfo({ ...@@ -71,10 +67,10 @@ async function parseModuleInfo({
} }
function addClientImport(path: string) { function addClientImport(path: string) {
if (isServerComponent(path) || hasFlightLoader(path, 'server')) { if (serverComponentRegex.test(path) || hasFlightLoader(path, 'server')) {
// If it's a server component, we recursively import its dependencies. // If it's a server component, we recursively import its dependencies.
imports.push(path) imports.push(path)
} else if (isClientComponent(path)) { } else if (clientComponentRegex.test(path)) {
// Client component. // Client component.
imports.push(path) imports.push(path)
} else { } else {
...@@ -102,7 +98,7 @@ async function parseModuleInfo({ ...@@ -102,7 +98,7 @@ async function parseModuleInfo({
if (!isClientCompilation) { if (!isClientCompilation) {
// Server compilation for .server.js. // Server compilation for .server.js.
if (isServerComponent(importSource)) { if (serverComponentRegex.test(importSource)) {
continue continue
} }
...@@ -111,7 +107,7 @@ async function parseModuleInfo({ ...@@ -111,7 +107,7 @@ async function parseModuleInfo({
node.source.span.start - beginPos node.source.span.start - beginPos
) )
if (isClientComponent(importSource)) { if (clientComponentRegex.test(importSource)) {
transformedSource += importDeclarations transformedSource += importDeclarations
transformedSource += JSON.stringify( transformedSource += JSON.stringify(
`next-flight-client-loader!${importSource}` `next-flight-client-loader!${importSource}`
...@@ -210,12 +206,10 @@ export default async function transformSource( ...@@ -210,12 +206,10 @@ export default async 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 isServerComponent = createServerComponentFilter()
const isClientComponent = createClientComponentFilter()
const hasAppliedFlightServerLoader = this.loaders.some((loader: any) => { const hasAppliedFlightServerLoader = this.loaders.some((loader: any) => {
return hasFlightLoader(loader.path, 'server') return hasFlightLoader(loader.path, 'server')
}) })
const isServerExt = isServerComponent(resourcePath) const isServerExt = serverComponentRegex.test(resourcePath)
if (!isClientCompilation) { if (!isClientCompilation) {
// We only apply the loader to server components, or shared components that // We only apply the loader to server components, or shared components that
...@@ -235,8 +229,6 @@ export default async function transformSource( ...@@ -235,8 +229,6 @@ export default async function transformSource(
resourcePath, resourcePath,
source, source,
isClientCompilation, isClientCompilation,
isServerComponent,
isClientComponent,
resolver, resolver,
}) })
......
...@@ -24,25 +24,18 @@ export function buildExports(moduleExports: any, isESM: boolean) { ...@@ -24,25 +24,18 @@ export function buildExports(moduleExports: any, isESM: boolean) {
return ret return ret
} }
export const createClientComponentFilter = () => { // Special cases for Next.js APIs that are considered as client components:
// Special cases for Next.js APIs that are considered as client components: // - .client.[ext]
// - .client.[ext] // - next built-in client components
// - next built-in client components // - .[imageExt]
// - .[imageExt] export const clientComponentRegex = new RegExp(
const regex = new RegExp( '(' +
'(' + `\\.client(\\.(${defaultJsFileExtensions.join('|')}))?|` +
`\\.client(\\.(${defaultJsFileExtensions.join('|')}))?|` + `next/(${nextClientComponents.join('|')})(\\.js)?|` +
`next/(${nextClientComponents.join('|')})(\\.js)?|` + `\\.(${imageExtensions.join('|')})` +
`\\.(${imageExtensions.join('|')})` + ')$'
')$' )
)
return (importSource: string) => regex.test(importSource)
}
export const createServerComponentFilter = () => { export const serverComponentRegex = new RegExp(
const regex = new RegExp( `\\.server(\\.(${defaultJsFileExtensions.join('|')}))?$`
`\\.server(\\.(${defaultJsFileExtensions.join('|')}))?$` )
)
return (importSource: string) => regex.test(importSource)
}
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { MIDDLEWARE_FLIGHT_MANIFEST } from '../../../shared/lib/constants' import { MIDDLEWARE_FLIGHT_MANIFEST } from '../../../shared/lib/constants'
import { createClientComponentFilter } from '../loaders/utils' import { clientComponentRegex } from '../loaders/utils'
// This is the module that will be used to anchor all client references to. // This is the module that will be used to anchor all client references to.
// I.e. it will have all the client files as async deps from this point on. // I.e. it will have all the client files as async deps from this point on.
...@@ -19,20 +19,25 @@ import { createClientComponentFilter } from '../loaders/utils' ...@@ -19,20 +19,25 @@ import { createClientComponentFilter } from '../loaders/utils'
type Options = { type Options = {
dev: boolean dev: boolean
pageExtensions: string[] pageExtensions: string[]
isEdgeServer: boolean
} }
const PLUGIN_NAME = 'FlightManifestPlugin' const PLUGIN_NAME = 'FlightManifestPlugin'
const isClientComponent = createClientComponentFilter() let edgeFlightManifest = {}
let nodeFlightManifest = {}
export class FlightManifestPlugin { export class FlightManifestPlugin {
dev: boolean = false dev: boolean = false
pageExtensions: string[] pageExtensions: string[]
isEdgeServer: boolean
constructor(options: Options) { constructor(options: Options) {
if (typeof options.dev === 'boolean') { if (typeof options.dev === 'boolean') {
this.dev = options.dev this.dev = options.dev
} }
this.pageExtensions = options.pageExtensions this.pageExtensions = options.pageExtensions
this.isEdgeServer = options.isEdgeServer
} }
apply(compiler: any) { apply(compiler: any) {
...@@ -72,9 +77,14 @@ export class FlightManifestPlugin { ...@@ -72,9 +77,14 @@ export class FlightManifestPlugin {
// TODO: Hook into deps instead of the target module. // TODO: Hook into deps instead of the target module.
// That way we know by the type of dep whether to include. // That way we know by the type of dep whether to include.
// It also resolves conflicts when the same module is in multiple chunks. // It also resolves conflicts when the same module is in multiple chunks.
if (!resource || !isClientComponent(resource)) { if (
!resource ||
!clientComponentRegex.test(resource) ||
!clientComponentRegex.test(id)
) {
return return
} }
const moduleExports: any = manifest[resource] || {} const moduleExports: any = manifest[resource] || {}
const exportsInfo = compilation.moduleGraph.getExportsInfo(mod) const exportsInfo = compilation.moduleGraph.getExportsInfo(mod)
...@@ -107,10 +117,13 @@ export class FlightManifestPlugin { ...@@ -107,10 +117,13 @@ export class FlightManifestPlugin {
for (const mod of chunkModules) { for (const mod of chunkModules) {
let modId = compilation.chunkGraph.getModuleId(mod) let modId = compilation.chunkGraph.getModuleId(mod)
// remove resource query on production if (typeof modId !== 'string') continue
if (typeof modId === 'string') {
modId = modId.split('?')[0] // Remove resource queries.
} modId = modId.split('?')[0]
// Remove the loader prefix.
modId = modId.split('next-flight-client-loader.js!')[1] || modId
recordModule(modId, chunk, mod) recordModule(modId, chunk, mod)
// If this is a concatenation, register each child to the parent ID. // If this is a concatenation, register each child to the parent ID.
if (mod.modules) { if (mod.modules) {
...@@ -124,8 +137,19 @@ export class FlightManifestPlugin { ...@@ -124,8 +137,19 @@ export class FlightManifestPlugin {
// With switchable runtime, we need to emit the manifest files for both // With switchable runtime, we need to emit the manifest files for both
// runtimes. // runtimes.
const file = `server/${MIDDLEWARE_FLIGHT_MANIFEST}` if (this.isEdgeServer) {
const json = JSON.stringify(manifest) edgeFlightManifest = manifest
} else {
nodeFlightManifest = manifest
}
const mergedManifest = {
...nodeFlightManifest,
...edgeFlightManifest,
}
const file =
(!this.dev && !this.isEdgeServer ? '../' : '') +
MIDDLEWARE_FLIGHT_MANIFEST
const json = JSON.stringify(mergedManifest)
assets[file + '.js'] = new sources.RawSource('self.__RSC_MANIFEST=' + json) assets[file + '.js'] = new sources.RawSource('self.__RSC_MANIFEST=' + json)
assets[file + '.json'] = new sources.RawSource(json) assets[file + '.json'] = new sources.RawSource(json)
......
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