Unverified Commit 9a36f337 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Simplify server CSS handling (#51018)

Remove the Server CSS manifest and related logic, and use the chunkGroup
CSS files instead for each entry to inject stylesheet links.

Why was that manifest needed in the first place? When implementing CSS
collection for RSC and nested layout initially, we collect CSS imports
at each layer and create corresponding client entries. But then soon got
hit by the problem of duplication and improper tree-shaking. Two layers
can have the same CSS imported so we solved it in a way that "if an
upper layer imports this module, skip it in child layers". Note that
this is deduped by module, so we need to keep the information of "layer
(entry) → CSS modules" somewhere, in a manifest.

Another reason is that we create the client entry before Webpack
optimizes modules, so we can inject the client entry into the same
compilation. But that means the collected client modules from the server
layer are not properly optimized (DCE). **This is a general issue at the
moment that's not specifically related to CSS, although using that
manifest to collect DCE'd info and join the original collected CSS files
with that info temporarily solved it.** That's why I disabled some tests
related to font CSS collection and want to improve it in a more general
way.

Why is that not needed anymore? Main reason is to keep a good balance
between duplication and number of chunks, and delegate the decision to
Webpack's splitChunks plugin. It is not possible to get to a point of 0
duplication unless we ship every CSS module as a single chunk. And since
in #50406 we made the duplication better but at the chunk asset level,
instead of the original module level.

Prior work: #50406, #50610.
parent f7c105d3
...@@ -16,10 +16,7 @@ declare global { ...@@ -16,10 +16,7 @@ declare global {
import type { Ipc } from '@vercel/turbopack-node/ipc/index' import type { Ipc } from '@vercel/turbopack-node/ipc/index'
import type { IncomingMessage } from 'node:http' import type { IncomingMessage } from 'node:http'
import type { import type { ClientReferenceManifest } from 'next/dist/build/webpack/plugins/flight-manifest-plugin'
ClientCSSReferenceManifest,
ClientReferenceManifest,
} from 'next/dist/build/webpack/plugins/flight-manifest-plugin'
import type { RenderData } from 'types/turbopack' import type { RenderData } from 'types/turbopack'
import type { RenderOpts } from 'next/dist/server/app-render/types' import type { RenderOpts } from 'next/dist/server/app-render/types'
...@@ -139,10 +136,11 @@ async function runOperation(renderData: RenderData) { ...@@ -139,10 +136,11 @@ async function runOperation(renderData: RenderData) {
} }
const proxyMethodsNested = ( const proxyMethodsNested = (
type: 'ssrModuleMapping' | 'clientModules' type: 'ssrModuleMapping' | 'clientModules' | 'entryCSSFiles'
): ProxyHandler< ): ProxyHandler<
| ClientReferenceManifest['ssrModuleMapping'] | ClientReferenceManifest['ssrModuleMapping']
| ClientReferenceManifest['clientModules'] | ClientReferenceManifest['clientModules']
| ClientReferenceManifest['entryCSSFiles']
> => { > => {
return { return {
get(_target, key: string) { get(_target, key: string) {
...@@ -170,6 +168,14 @@ async function runOperation(renderData: RenderData) { ...@@ -170,6 +168,14 @@ async function runOperation(renderData: RenderData) {
chunks: JSON.parse(id)[1], chunks: JSON.parse(id)[1],
} }
} }
if (type === 'entryCSSFiles') {
const cssChunks = JSON.parse(key)
// TODO(WEB-856) subscribe to changes
return {
modules: [],
files: cssChunks.filter(filterAvailable).map(toPath),
}
}
}, },
} }
} }
...@@ -183,6 +189,10 @@ async function runOperation(renderData: RenderData) { ...@@ -183,6 +189,10 @@ async function runOperation(renderData: RenderData) {
{}, {},
proxyMethodsNested('ssrModuleMapping') proxyMethodsNested('ssrModuleMapping')
) )
const entryCSSFilesProxy = new Proxy(
{},
proxyMethodsNested('entryCSSFiles')
)
return { return {
get(_target: any, prop: string) { get(_target: any, prop: string) {
if (prop === 'ssrModuleMapping') { if (prop === 'ssrModuleMapping') {
...@@ -191,6 +201,9 @@ async function runOperation(renderData: RenderData) { ...@@ -191,6 +201,9 @@ async function runOperation(renderData: RenderData) {
if (prop === 'clientModules') { if (prop === 'clientModules') {
return clientModulesProxy return clientModulesProxy
} }
if (prop === 'entryCSSFiles') {
return entryCSSFilesProxy
}
}, },
} }
} }
...@@ -216,24 +229,8 @@ async function runOperation(renderData: RenderData) { ...@@ -216,24 +229,8 @@ async function runOperation(renderData: RenderData) {
return needed return needed
} }
} }
const cssImportProxyMethods = {
get(_target: any, prop: string) {
const cssChunks = JSON.parse(prop.replace(/\.js$/, ''))
// TODO(WEB-856) subscribe to changes
// This return value is passed to proxyMethodsNested for clientModules
return cssChunks
.filter(filterAvailable)
.map(toPath)
.map((chunk: string) => JSON.stringify([chunk, [chunk]]))
},
}
const manifest: ClientReferenceManifest = new Proxy({} as any, proxyMethods()) const manifest: ClientReferenceManifest = new Proxy({} as any, proxyMethods())
const serverCSSManifest: ClientCSSReferenceManifest = {
cssImports: new Proxy({} as any, cssImportProxyMethods),
cssModules: {},
}
const req: IncomingMessage = { const req: IncomingMessage = {
url: renderData.originalUrl, url: renderData.originalUrl,
method: renderData.method, method: renderData.method,
...@@ -275,7 +272,6 @@ async function runOperation(renderData: RenderData) { ...@@ -275,7 +272,6 @@ async function runOperation(renderData: RenderData) {
pages: ['page.js'], pages: ['page.js'],
}, },
clientReferenceManifest: manifest, clientReferenceManifest: manifest,
serverCSSManifest,
runtime: 'nodejs', runtime: 'nodejs',
serverComponents: true, serverComponents: true,
assetPrefix: '', assetPrefix: '',
......
...@@ -62,7 +62,6 @@ import { ...@@ -62,7 +62,6 @@ import {
APP_PATHS_MANIFEST, APP_PATHS_MANIFEST,
APP_PATH_ROUTES_MANIFEST, APP_PATH_ROUTES_MANIFEST,
APP_BUILD_MANIFEST, APP_BUILD_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST,
RSC_MODULE_TYPES, RSC_MODULE_TYPES,
NEXT_FONT_MANIFEST, NEXT_FONT_MANIFEST,
SUBRESOURCE_INTEGRITY_MANIFEST, SUBRESOURCE_INTEGRITY_MANIFEST,
...@@ -893,14 +892,6 @@ export default async function build( ...@@ -893,14 +892,6 @@ export default async function build(
SERVER_DIRECTORY, SERVER_DIRECTORY,
CLIENT_REFERENCE_MANIFEST + '.json' CLIENT_REFERENCE_MANIFEST + '.json'
), ),
path.join(
SERVER_DIRECTORY,
FLIGHT_SERVER_CSS_MANIFEST + '.js'
),
path.join(
SERVER_DIRECTORY,
FLIGHT_SERVER_CSS_MANIFEST + '.json'
),
path.join( path.join(
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST + '.js' SERVER_REFERENCE_MANIFEST + '.js'
......
...@@ -151,7 +151,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -151,7 +151,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
const prerenderManifest = maybeJSONParse(self.__PRERENDER_MANIFEST) const prerenderManifest = maybeJSONParse(self.__PRERENDER_MANIFEST)
const reactLoadableManifest = maybeJSONParse(self.__REACT_LOADABLE_MANIFEST) const reactLoadableManifest = maybeJSONParse(self.__REACT_LOADABLE_MANIFEST)
const rscManifest = maybeJSONParse(self.__RSC_MANIFEST) const rscManifest = maybeJSONParse(self.__RSC_MANIFEST)
const rscCssManifest = maybeJSONParse(self.__RSC_CSS_MANIFEST)
const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST) const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)
const subresourceIntegrityManifest = ${ const subresourceIntegrityManifest = ${
sriEnabled sriEnabled
...@@ -176,7 +175,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -176,7 +175,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
pagesRenderToHTML, pagesRenderToHTML,
reactLoadableManifest, reactLoadableManifest,
clientReferenceManifest: ${isServerComponent} ? rscManifest : null, clientReferenceManifest: ${isServerComponent} ? rscManifest : null,
serverCSSManifest: ${isServerComponent} ? rscCssManifest : null,
serverActionsManifest: ${isServerComponent} ? rscServerManifest : null, serverActionsManifest: ${isServerComponent} ? rscServerManifest : null,
subresourceIntegrityManifest, subresourceIntegrityManifest,
config: ${stringifiedConfig}, config: ${stringifiedConfig},
......
...@@ -31,7 +31,6 @@ export function getRender({ ...@@ -31,7 +31,6 @@ export function getRender({
pagesRenderToHTML, pagesRenderToHTML,
clientReferenceManifest, clientReferenceManifest,
subresourceIntegrityManifest, subresourceIntegrityManifest,
serverCSSManifest,
serverActionsManifest, serverActionsManifest,
config, config,
buildId, buildId,
...@@ -53,7 +52,6 @@ export function getRender({ ...@@ -53,7 +52,6 @@ export function getRender({
reactLoadableManifest: ReactLoadableManifest reactLoadableManifest: ReactLoadableManifest
subresourceIntegrityManifest?: Record<string, string> subresourceIntegrityManifest?: Record<string, string>
clientReferenceManifest?: ClientReferenceManifest clientReferenceManifest?: ClientReferenceManifest
serverCSSManifest: any
serverActionsManifest: any serverActionsManifest: any
appServerMod: any appServerMod: any
config: NextConfigComplete config: NextConfigComplete
...@@ -88,7 +86,6 @@ export function getRender({ ...@@ -88,7 +86,6 @@ export function getRender({
supportsDynamicHTML: true, supportsDynamicHTML: true,
disableOptimizedLoading: true, disableOptimizedLoading: true,
clientReferenceManifest, clientReferenceManifest,
serverCSSManifest,
serverActionsManifest, serverActionsManifest,
}, },
appRenderToHTML, appRenderToHTML,
......
...@@ -3,7 +3,6 @@ import type { ...@@ -3,7 +3,6 @@ import type {
ClientComponentImports, ClientComponentImports,
NextFlightClientEntryLoaderOptions, NextFlightClientEntryLoaderOptions,
} from '../loaders/next-flight-client-entry-loader' } from '../loaders/next-flight-client-entry-loader'
import type { ClientCSSReferenceManifest } from './flight-manifest-plugin'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
import { stringify } from 'querystring' import { stringify } from 'querystring'
...@@ -21,7 +20,6 @@ import { ...@@ -21,7 +20,6 @@ import {
COMPILER_NAMES, COMPILER_NAMES,
EDGE_RUNTIME_WEBPACK, EDGE_RUNTIME_WEBPACK,
SERVER_REFERENCE_MANIFEST, SERVER_REFERENCE_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST,
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import { import {
generateActionId, generateActionId,
...@@ -76,10 +74,6 @@ const pluginState = getProxiedPluginState({ ...@@ -76,10 +74,6 @@ const pluginState = getProxiedPluginState({
} }
>, >,
// Manifest of CSS entry files for server/edge server.
serverCSSManifest: {} as ClientCSSReferenceManifest,
edgeServerCSSManifest: {} as ClientCSSReferenceManifest,
// Mapping of resource path to module id for server/edge server. // Mapping of resource path to module id for server/edge server.
serverModuleIds: {} as Record<string, string | number>, serverModuleIds: {} as Record<string, string | number>,
edgeServerModuleIds: {} as Record<string, string | number>, edgeServerModuleIds: {} as Record<string, string | number>,
...@@ -308,7 +302,6 @@ export class ClientReferenceEntryPlugin { ...@@ -308,7 +302,6 @@ export class ClientReferenceEntryPlugin {
compilation, compilation,
entryName: name, entryName: name,
clientComponentImports, clientComponentImports,
cssImports,
bundlePath, bundlePath,
absolutePagePath: entryRequest, absolutePagePath: entryRequest,
}) })
...@@ -475,121 +468,6 @@ export class ClientReferenceEntryPlugin { ...@@ -475,121 +468,6 @@ export class ClientReferenceEntryPlugin {
return Promise.all(addedClientActionEntryList) return Promise.all(addedClientActionEntryList)
}) })
// After optimizing all the modules, we collect the CSS that are still used
// by the certain chunk.
compilation.hooks.afterOptimizeModules.tap(PLUGIN_NAME, () => {
const cssImportsForChunk: Record<string, Set<string>> = {}
const cssManifest = this.isEdgeServer
? pluginState.edgeServerCSSManifest
: pluginState.serverCSSManifest
function collectModule(entryName: string, mod: any) {
const resource = mod.resource
const modId = resource
if (modId) {
if (isCSSMod(mod)) {
cssImportsForChunk[entryName].add(modId)
}
}
}
compilation.chunkGroups.forEach((chunkGroup: any) => {
chunkGroup.chunks.forEach((chunk: webpack.Chunk) => {
// Here we only track page chunks.
if (!chunk.name) return
if (!chunk.name.endsWith('/page')) return
const entryName = path.join(this.appDir, '..', chunk.name)
if (!cssImportsForChunk[entryName]) {
cssImportsForChunk[entryName] = new Set()
}
const chunkModules = compilation.chunkGraph.getChunkModulesIterable(
chunk
) as Iterable<webpack.NormalModule>
for (const mod of chunkModules) {
collectModule(entryName, mod)
const anyModule = mod as any
if (anyModule.modules) {
anyModule.modules.forEach((concatenatedMod: any) => {
collectModule(entryName, concatenatedMod)
})
}
}
const entryCSSInfo: Record<string, string[]> =
cssManifest.cssModules || {}
entryCSSInfo[entryName] = [...cssImportsForChunk[entryName]]
cssManifest.cssModules = entryCSSInfo
})
})
forEachEntryModule(compilation, ({ name, entryModule }) => {
const clientEntryDependencyMap = collectClientEntryDependencyMap(name)
const tracked = new Set<string>()
const mergedCSSimports: CssImports = {}
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 { cssImports } = this.collectComponentInfoFromDependencies({
entryRequest,
compilation,
dependency: entryDependency,
clientEntryDependencyMap,
})
Object.assign(mergedCSSimports, cssImports)
}
if (!cssManifest.cssImports) cssManifest.cssImports = {}
Object.assign(
cssManifest.cssImports,
deduplicateCSSImportsForEntry(mergedCSSimports)
)
})
})
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
},
(assets: webpack.Compilation['assets']) => {
const data: ClientCSSReferenceManifest = {
cssImports: {
...pluginState.serverCSSManifest.cssImports,
...pluginState.edgeServerCSSManifest.cssImports,
},
cssModules: {
...pluginState.serverCSSManifest.cssModules,
...pluginState.edgeServerCSSManifest.cssModules,
},
}
const manifest = JSON.stringify(data, null, this.dev ? 2 : undefined)
assets[`${this.assetPrefix}${FLIGHT_SERVER_CSS_MANIFEST}.json`] =
new sources.RawSource(
manifest
) as unknown as webpack.sources.RawSource
assets[`${this.assetPrefix}${FLIGHT_SERVER_CSS_MANIFEST}.js`] =
new sources.RawSource(
`self.__RSC_CSS_MANIFEST=${JSON.stringify(manifest)}`
) as unknown as webpack.sources.RawSource
}
)
// Invalidate in development to trigger recompilation // Invalidate in development to trigger recompilation
const invalidator = getInvalidator(compiler.outputPath) const invalidator = getInvalidator(compiler.outputPath)
// Check if any of the entry injections need an invalidation // Check if any of the entry injections need an invalidation
......
...@@ -18,7 +18,6 @@ import { getProxiedPluginState } from '../../build-context' ...@@ -18,7 +18,6 @@ import { getProxiedPluginState } from '../../build-context'
import { traverseModules } from '../utils' import { traverseModules } from '../utils'
import { nonNullable } from '../../../lib/non-nullable' import { nonNullable } from '../../../lib/non-nullable'
import { WEBPACK_LAYERS } from '../../../lib/constants' import { WEBPACK_LAYERS } from '../../../lib/constants'
import { getClientReferenceModuleKey } from '../../../lib/client-reference'
interface Options { interface Options {
dev: boolean dev: boolean
...@@ -69,14 +68,11 @@ export type ClientReferenceManifest = { ...@@ -69,14 +68,11 @@ export type ClientReferenceManifest = {
edgeSSRModuleMapping: { edgeSSRModuleMapping: {
[moduleId: string]: ManifestNode [moduleId: string]: ManifestNode
} }
} entryCSSFiles: {
[entry: string]: {
export type ClientCSSReferenceManifest = { modules: string[]
cssImports: { files: string[]
[modulePath: string]: string[] }
}
cssModules?: {
[entry: string]: string[]
} }
} }
...@@ -85,11 +81,13 @@ const PLUGIN_NAME = 'ClientReferenceManifestPlugin' ...@@ -85,11 +81,13 @@ const PLUGIN_NAME = 'ClientReferenceManifestPlugin'
export class ClientReferenceManifestPlugin { export class ClientReferenceManifestPlugin {
dev: Options['dev'] = false dev: Options['dev'] = false
appDir: Options['appDir'] appDir: Options['appDir']
appDirBase: string
ASYNC_CLIENT_MODULES: Set<string> ASYNC_CLIENT_MODULES: Set<string>
constructor(options: Options) { constructor(options: Options) {
this.dev = options.dev this.dev = options.dev
this.appDir = options.appDir this.appDir = options.appDir
this.appDirBase = path.dirname(this.appDir) + path.sep
this.ASYNC_CLIENT_MODULES = new Set(pluginState.ASYNC_CLIENT_MODULES) this.ASYNC_CLIENT_MODULES = new Set(pluginState.ASYNC_CLIENT_MODULES)
} }
...@@ -130,6 +128,7 @@ export class ClientReferenceManifestPlugin { ...@@ -130,6 +128,7 @@ export class ClientReferenceManifestPlugin {
ssrModuleMapping: {}, ssrModuleMapping: {},
edgeSSRModuleMapping: {}, edgeSSRModuleMapping: {},
clientModules: {}, clientModules: {},
entryCSSFiles: {},
} }
const clientRequestsSet = new Set() const clientRequestsSet = new Set()
...@@ -172,11 +171,24 @@ export class ClientReferenceManifestPlugin { ...@@ -172,11 +171,24 @@ export class ClientReferenceManifestPlugin {
} }
const requiredChunks = getAppPathRequiredChunks() const requiredChunks = getAppPathRequiredChunks()
const recordModule = ( let chunkEntryName: string | null = null
id: ModuleId, if (chunkGroup.name && /^app[\\/]/.test(chunkGroup.name)) {
mod: webpack.NormalModule, // Absolute path without the extension
chunkCSS: string[] chunkEntryName = (this.appDirBase + chunkGroup.name).replace(
) => { /[\\/]/g,
path.sep
)
manifest.entryCSSFiles[chunkEntryName] = {
modules: [],
files: chunkGroup
.getFiles()
.filter(
(f) => !f.startsWith('static/css/pages/') && f.endsWith('.css')
),
}
}
const recordModule = (id: ModuleId, mod: webpack.NormalModule) => {
const isCSSModule = isCSSMod(mod) const isCSSModule = isCSSMod(mod)
// Skip all modules from the pages folder. CSS modules are a special case // Skip all modules from the pages folder. CSS modules are a special case
...@@ -196,6 +208,13 @@ export class ClientReferenceManifestPlugin { ...@@ -196,6 +208,13 @@ export class ClientReferenceManifestPlugin {
return return
} }
if (isCSSModule) {
if (chunkEntryName) {
manifest.entryCSSFiles[chunkEntryName].modules.push(resource)
}
return
}
const moduleReferences = manifest.clientModules const moduleReferences = manifest.clientModules
const moduleIdMapping = manifest.ssrModuleMapping const moduleIdMapping = manifest.ssrModuleMapping
const edgeModuleIdMapping = manifest.edgeSSRModuleMapping const edgeModuleIdMapping = manifest.edgeSSRModuleMapping
...@@ -211,26 +230,6 @@ export class ClientReferenceManifestPlugin { ...@@ -211,26 +230,6 @@ export class ClientReferenceManifestPlugin {
if (!ssrNamedModuleId.startsWith('.')) if (!ssrNamedModuleId.startsWith('.'))
ssrNamedModuleId = `./${ssrNamedModuleId.replace(/\\/g, '/')}` ssrNamedModuleId = `./${ssrNamedModuleId.replace(/\\/g, '/')}`
if (isCSSModule) {
const exportName = getClientReferenceModuleKey(resource, '')
if (!moduleReferences[exportName]) {
moduleReferences[exportName] = {
id: id || '',
name: 'default',
chunks: chunkCSS,
}
} else {
// It is possible that there are multiple modules with the same resource,
// e.g. extracted by mini-css-extract-plugin. In that case we need to
// merge the chunks.
moduleReferences[exportName].chunks = [
...new Set([...moduleReferences[exportName].chunks, ...chunkCSS]),
]
}
return
}
// Only apply following logic to client module requests from client entry, // Only apply following logic to client module requests from client entry,
// or if the module is marked as client module. // or if the module is marked as client module.
if ( if (
...@@ -312,25 +311,28 @@ export class ClientReferenceManifestPlugin { ...@@ -312,25 +311,28 @@ export class ClientReferenceManifestPlugin {
// TODO: Update type so that it doesn't have to be cast. // TODO: Update type so that it doesn't have to be cast.
) as Iterable<webpack.NormalModule> ) as Iterable<webpack.NormalModule>
const chunkCSS = [...chunk.files].filter(
(f) => !f.startsWith('static/css/pages/') && f.endsWith('.css')
)
for (const mod of chunkModules) { for (const mod of chunkModules) {
const modId: string = compilation.chunkGraph.getModuleId(mod) + '' const modId: string = compilation.chunkGraph.getModuleId(mod) + ''
recordModule(modId, mod, chunkCSS) recordModule(modId, 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.
// TODO: remove any // TODO: remove any
const anyModule = mod as any const anyModule = mod as any
if (anyModule.modules) { if (anyModule.modules) {
anyModule.modules.forEach((concatenatedMod: any) => { anyModule.modules.forEach((concatenatedMod: any) => {
recordModule(modId, concatenatedMod, chunkCSS) recordModule(modId, concatenatedMod)
}) })
} }
} }
}) })
if (chunkEntryName) {
// Make sure CSS modules are deduped
manifest.entryCSSFiles[chunkEntryName].modules = [
...new Set(manifest.entryCSSFiles[chunkEntryName].modules),
]
}
}) })
const file = 'server/' + CLIENT_REFERENCE_MANIFEST const file = 'server/' + CLIENT_REFERENCE_MANIFEST
......
...@@ -17,7 +17,6 @@ import { ...@@ -17,7 +17,6 @@ import {
MIDDLEWARE_MANIFEST, MIDDLEWARE_MANIFEST,
MIDDLEWARE_REACT_LOADABLE_MANIFEST, MIDDLEWARE_REACT_LOADABLE_MANIFEST,
NEXT_CLIENT_SSR_ENTRY_SUFFIX, NEXT_CLIENT_SSR_ENTRY_SUFFIX,
FLIGHT_SERVER_CSS_MANIFEST,
SUBRESOURCE_INTEGRITY_MANIFEST, SUBRESOURCE_INTEGRITY_MANIFEST,
NEXT_FONT_MANIFEST, NEXT_FONT_MANIFEST,
SERVER_REFERENCE_MANIFEST, SERVER_REFERENCE_MANIFEST,
...@@ -97,7 +96,6 @@ function getEntryFiles( ...@@ -97,7 +96,6 @@ function getEntryFiles(
if (meta.edgeSSR.isServerComponent) { if (meta.edgeSSR.isServerComponent) {
files.push(`server/${SERVER_REFERENCE_MANIFEST}.js`) files.push(`server/${SERVER_REFERENCE_MANIFEST}.js`)
files.push(`server/${CLIENT_REFERENCE_MANIFEST}.js`) files.push(`server/${CLIENT_REFERENCE_MANIFEST}.js`)
files.push(`server/${FLIGHT_SERVER_CSS_MANIFEST}.js`)
if (opts.sriEnabled) { if (opts.sriEnabled) {
files.push(`server/${SUBRESOURCE_INTEGRITY_MANIFEST}.js`) files.push(`server/${SUBRESOURCE_INTEGRITY_MANIFEST}.js`)
} }
......
...@@ -25,7 +25,6 @@ import { ...@@ -25,7 +25,6 @@ import {
EXPORT_DETAIL, EXPORT_DETAIL,
EXPORT_MARKER, EXPORT_MARKER,
CLIENT_REFERENCE_MANIFEST, CLIENT_REFERENCE_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST,
NEXT_FONT_MANIFEST, NEXT_FONT_MANIFEST,
MIDDLEWARE_MANIFEST, MIDDLEWARE_MANIFEST,
PAGES_MANIFEST, PAGES_MANIFEST,
...@@ -486,11 +485,6 @@ export default async function exportApp( ...@@ -486,11 +485,6 @@ export default async function exportApp(
SERVER_DIRECTORY, SERVER_DIRECTORY,
CLIENT_REFERENCE_MANIFEST + '.json' CLIENT_REFERENCE_MANIFEST + '.json'
)), )),
serverCSSManifest: require(join(
distDir,
SERVER_DIRECTORY,
FLIGHT_SERVER_CSS_MANIFEST + '.json'
)),
serverActionsManifest: require(join( serverActionsManifest: require(join(
distDir, distDir,
SERVER_DIRECTORY, SERVER_DIRECTORY,
......
...@@ -383,6 +383,18 @@ export async function handleAction({ ...@@ -383,6 +383,18 @@ export async function handleAction({
} }
} }
// actions.js
// app/page.js
// action woker1
// appRender1
// app/foo/page.js
// action worker2
// appRender
// / -> fire action -> POST / -> appRender1 -> modId for the action file
// /foo -> fire action -> POST /foo -> appRender2 -> modId for the action file
const actionModId = const actionModId =
serverActionsManifest[ serverActionsManifest[
process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node' process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'
......
...@@ -59,7 +59,6 @@ import { createErrorHandler } from './create-error-handler' ...@@ -59,7 +59,6 @@ import { createErrorHandler } from './create-error-handler'
import { getShortDynamicParamType } from './get-short-dynamic-param-type' import { getShortDynamicParamType } from './get-short-dynamic-param-type'
import { getSegmentParam } from './get-segment-param' import { getSegmentParam } from './get-segment-param'
import { getCssInlinedLinkTags } from './get-css-inlined-link-tags' import { getCssInlinedLinkTags } from './get-css-inlined-link-tags'
import { getServerCSSForEntries } from './get-server-css-for-entries'
import { getPreloadableFonts } from './get-preloadable-fonts' import { getPreloadableFonts } from './get-preloadable-fonts'
import { getScriptNonceFromHeader } from './get-script-nonce-from-header' import { getScriptNonceFromHeader } from './get-script-nonce-from-header'
import { renderToString } from './render-to-string' import { renderToString } from './render-to-string'
...@@ -162,7 +161,6 @@ export async function renderToHTMLOrFlight( ...@@ -162,7 +161,6 @@ export async function renderToHTMLOrFlight(
const appUsingSizeAdjust = nextFontManifest?.appUsingSizeAdjust const appUsingSizeAdjust = nextFontManifest?.appUsingSizeAdjust
const clientReferenceManifest = renderOpts.clientReferenceManifest! const clientReferenceManifest = renderOpts.clientReferenceManifest!
const serverCSSManifest = renderOpts.serverCSSManifest!
const capturedErrors: Error[] = [] const capturedErrors: Error[] = []
const allCapturedErrors: Error[] = [] const allCapturedErrors: Error[] = []
...@@ -358,15 +356,6 @@ export async function renderToHTMLOrFlight( ...@@ -358,15 +356,6 @@ export async function renderToHTMLOrFlight(
let defaultRevalidate: false | undefined | number = false let defaultRevalidate: false | undefined | number = false
// Collect all server CSS imports used by this specific entry (or entries, for parallel routes).
// Not that we can't rely on the CSS manifest because it tracks CSS imports per module,
// which can be used by multiple entries and cannot be tree-shaked in the module graph.
// More info: https://github.com/vercel/next.js/issues/41018
const serverCSSForEntries = getServerCSSForEntries(
serverCSSManifest!,
ComponentMod.pages
)
const assetPrefix = renderOpts.assetPrefix || '' const assetPrefix = renderOpts.assetPrefix || ''
const getAssetQueryString = (addTimestamp: boolean) => { const getAssetQueryString = (addTimestamp: boolean) => {
...@@ -396,9 +385,7 @@ export async function renderToHTMLOrFlight( ...@@ -396,9 +385,7 @@ export async function renderToHTMLOrFlight(
}): Promise<any> => { }): Promise<any> => {
const cssHrefs = getCssInlinedLinkTags( const cssHrefs = getCssInlinedLinkTags(
clientReferenceManifest, clientReferenceManifest,
serverCSSManifest!,
filePath, filePath,
serverCSSForEntries,
injectedCSS injectedCSS
) )
...@@ -455,9 +442,7 @@ export async function renderToHTMLOrFlight( ...@@ -455,9 +442,7 @@ export async function renderToHTMLOrFlight(
const stylesheets: string[] = layoutOrPagePath const stylesheets: string[] = layoutOrPagePath
? getCssInlinedLinkTags( ? getCssInlinedLinkTags(
clientReferenceManifest, clientReferenceManifest,
serverCSSManifest!,
layoutOrPagePath, layoutOrPagePath,
serverCSSForEntries,
injectedCSSWithCurrentLayout, injectedCSSWithCurrentLayout,
true true
) )
...@@ -465,9 +450,8 @@ export async function renderToHTMLOrFlight( ...@@ -465,9 +450,8 @@ export async function renderToHTMLOrFlight(
const preloadedFontFiles = layoutOrPagePath const preloadedFontFiles = layoutOrPagePath
? getPreloadableFonts( ? getPreloadableFonts(
serverCSSManifest!, clientReferenceManifest,
nextFontManifest, nextFontManifest,
serverCSSForEntries,
layoutOrPagePath, layoutOrPagePath,
injectedFontPreloadTagsWithCurrentLayout injectedFontPreloadTagsWithCurrentLayout
) )
...@@ -1114,16 +1098,13 @@ export async function renderToHTMLOrFlight( ...@@ -1114,16 +1098,13 @@ export async function renderToHTMLOrFlight(
if (layoutPath) { if (layoutPath) {
getCssInlinedLinkTags( getCssInlinedLinkTags(
clientReferenceManifest, clientReferenceManifest,
serverCSSManifest!,
layoutPath, layoutPath,
serverCSSForEntries,
injectedCSSWithCurrentLayout, injectedCSSWithCurrentLayout,
true true
) )
getPreloadableFonts( getPreloadableFonts(
serverCSSManifest!, clientReferenceManifest,
nextFontManifest, nextFontManifest,
serverCSSForEntries,
layoutPath, layoutPath,
injectedFontPreloadTagsWithCurrentLayout injectedFontPreloadTagsWithCurrentLayout
) )
......
import { import { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
ClientCSSReferenceManifest,
ClientReferenceManifest,
} from '../../build/webpack/plugins/flight-manifest-plugin'
import { getClientReferenceModuleKey } from '../../lib/client-reference'
/** /**
* Get external stylesheet link hrefs based on server CSS manifest. * Get external stylesheet link hrefs based on server CSS manifest.
*/ */
export function getCssInlinedLinkTags( export function getCssInlinedLinkTags(
clientReferenceManifest: ClientReferenceManifest, clientReferenceManifest: ClientReferenceManifest,
serverCSSManifest: ClientCSSReferenceManifest,
filePath: string, filePath: string,
serverCSSForEntries: string[],
injectedCSS: Set<string>, injectedCSS: Set<string>,
collectNewCSSImports?: boolean collectNewCSSImports?: boolean
): string[] { ): string[] {
const layoutOrPageCssModules = serverCSSManifest.cssImports[filePath] const filePathWithoutExt = filePath.replace(/\.[^.]+$/, '')
const filePathWithoutExt = filePath.replace(/(\.[A-Za-z0-9]+)+$/, '')
if (!layoutOrPageCssModules) {
return []
}
const chunks = new Set<string>() const chunks = new Set<string>()
const isNotFoundPage = /(\/|\\)not-found/.test(filePathWithoutExt) const entryCSSFiles =
clientReferenceManifest.entryCSSFiles[filePathWithoutExt]
for (const mod of layoutOrPageCssModules) {
// We only include the CSS if it's a global CSS, or it is used by this
// entrypoint (CSS files that actually affect this layer).
const isGlobalCSS = !/\.module\.(css|sass|scss)$/.test(mod)
// For not-found pages, it will generally match all non-existing entries so
// even if `serverCSSForEntries` is empty, we still want to include the CSS.
const isImportedByEntry =
serverCSSForEntries.includes(mod) || isNotFoundPage
if (isImportedByEntry || isGlobalCSS) { if (entryCSSFiles) {
// If the CSS is already injected by a parent layer, we don't need for (const file of entryCSSFiles.files) {
// to inject it again. if (!injectedCSS.has(file)) {
if (!injectedCSS.has(mod)) { if (collectNewCSSImports) {
const modData = injectedCSS.add(file)
clientReferenceManifest.clientModules[
getClientReferenceModuleKey(mod, '')
]
if (modData) {
for (const chunk of modData.chunks) {
chunks.add(chunk)
// This might be a new layout, and to make it more efficient and
// not introducing another loop, we mutate the set directly.
if (collectNewCSSImports) {
injectedCSS.add(mod)
}
}
} }
chunks.add(file)
} }
} }
} }
......
import { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import { ClientCSSReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' import { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
/** /**
* Get hrefs for fonts to preload * Get hrefs for fonts to preload
...@@ -9,35 +9,33 @@ import { ClientCSSReferenceManifest } from '../../build/webpack/plugins/flight-m ...@@ -9,35 +9,33 @@ import { ClientCSSReferenceManifest } from '../../build/webpack/plugins/flight-m
* Returns null if there are fonts but none to preload and at least some were previously preloaded * Returns null if there are fonts but none to preload and at least some were previously preloaded
*/ */
export function getPreloadableFonts( export function getPreloadableFonts(
serverCSSManifest: ClientCSSReferenceManifest, clientReferenceManifest: ClientReferenceManifest,
nextFontManifest: NextFontManifest | undefined, nextFontManifest: NextFontManifest | undefined,
serverCSSForEntries: string[],
filePath: string | undefined, filePath: string | undefined,
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
): string[] | null { ): string[] | null {
if (!nextFontManifest || !filePath) { if (!nextFontManifest || !filePath) {
return null return null
} }
const layoutOrPageCss = serverCSSManifest.cssImports[filePath] const filepathWithoutExtension = filePath.replace(/\.[^.]+$/, '')
const entryCSS =
clientReferenceManifest.entryCSSFiles[filepathWithoutExtension]
if (!layoutOrPageCss) { if (!entryCSS) {
return null return null
} }
const fontFiles = new Set<string>() const fontFiles = new Set<string>()
let foundFontUsage = false let foundFontUsage = false
for (const css of layoutOrPageCss) { for (const cssModules of entryCSS.modules) {
// We only include the CSS if it is used by this entrypoint. const preloadedFontFiles = nextFontManifest.app[cssModules]
if (serverCSSForEntries.includes(css)) { if (preloadedFontFiles) {
const preloadedFontFiles = nextFontManifest.app[css] foundFontUsage = true
if (preloadedFontFiles) { for (const fontFile of preloadedFontFiles) {
foundFontUsage = true if (!injectedFontPreloadTags.has(fontFile)) {
for (const fontFile of preloadedFontFiles) { fontFiles.add(fontFile)
if (!injectedFontPreloadTags.has(fontFile)) { injectedFontPreloadTags.add(fontFile)
fontFiles.add(fontFile)
injectedFontPreloadTags.add(fontFile)
}
} }
} }
} }
......
import { ClientCSSReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
export function getServerCSSForEntries(
serverCSSManifest: ClientCSSReferenceManifest,
entries: string[]
) {
const css = []
for (const entry of entries) {
const entryName = entry.replace(/\.[^.]+$/, '')
if (
serverCSSManifest.cssModules &&
serverCSSManifest.cssModules[entryName]
) {
css.push(...serverCSSManifest.cssModules[entryName])
}
}
return css
}
import type { LoadComponentsReturnType } from '../load-components' import type { LoadComponentsReturnType } from '../load-components'
import type { ServerRuntime } from '../../../types' import type { ServerRuntime } from '../../../types'
import type { import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
ClientCSSReferenceManifest,
ClientReferenceManifest,
} from '../../build/webpack/plugins/flight-manifest-plugin'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import zod from 'zod' import zod from 'zod'
...@@ -127,7 +124,6 @@ export type RenderOptsPartial = { ...@@ -127,7 +124,6 @@ export type RenderOptsPartial = {
dev?: boolean dev?: boolean
buildId: string buildId: string
clientReferenceManifest?: ClientReferenceManifest clientReferenceManifest?: ClientReferenceManifest
serverCSSManifest?: ClientCSSReferenceManifest
supportsDynamicHTML: boolean supportsDynamicHTML: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
serverComponents?: boolean serverComponents?: boolean
......
...@@ -246,7 +246,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -246,7 +246,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
supportsDynamicHTML?: boolean supportsDynamicHTML?: boolean
isBot?: boolean isBot?: boolean
clientReferenceManifest?: ClientReferenceManifest clientReferenceManifest?: ClientReferenceManifest
serverCSSManifest?: any
serverActionsManifest?: any serverActionsManifest?: any
nextFontManifest?: NextFontManifest nextFontManifest?: NextFontManifest
renderServerComponentData?: boolean renderServerComponentData?: boolean
...@@ -261,7 +260,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -261,7 +260,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected appPathRoutes?: Record<string, string[]> protected appPathRoutes?: Record<string, string[]>
protected customRoutes: CustomRoutes protected customRoutes: CustomRoutes
protected clientReferenceManifest?: ClientReferenceManifest protected clientReferenceManifest?: ClientReferenceManifest
protected serverCSSManifest?: any
protected nextFontManifest?: NextFontManifest protected nextFontManifest?: NextFontManifest
public readonly hostname?: string public readonly hostname?: string
public readonly port?: number public readonly port?: number
...@@ -286,7 +284,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -286,7 +284,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected abstract getFontManifest(): FontManifest | undefined protected abstract getFontManifest(): FontManifest | undefined
protected abstract getPrerenderManifest(): PrerenderManifest protected abstract getPrerenderManifest(): PrerenderManifest
protected abstract getServerComponentManifest(): any protected abstract getServerComponentManifest(): any
protected abstract getServerCSSManifest(): any
protected abstract getNextFontManifest(): NextFontManifest | undefined protected abstract getNextFontManifest(): NextFontManifest | undefined
protected abstract attachRequestMeta( protected abstract attachRequestMeta(
req: BaseNextRequest, req: BaseNextRequest,
...@@ -414,9 +411,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -414,9 +411,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
this.clientReferenceManifest = serverComponents this.clientReferenceManifest = serverComponents
? this.getServerComponentManifest() ? this.getServerComponentManifest()
: undefined : undefined
this.serverCSSManifest = serverComponents
? this.getServerCSSManifest()
: undefined
this.nextFontManifest = this.getNextFontManifest() this.nextFontManifest = this.getNextFontManifest()
if (process.env.NEXT_RUNTIME !== 'edge') { if (process.env.NEXT_RUNTIME !== 'edge') {
......
...@@ -1430,10 +1430,6 @@ export default class DevServer extends Server { ...@@ -1430,10 +1430,6 @@ export default class DevServer extends Server {
return undefined return undefined
} }
protected getServerCSSManifest() {
return undefined
}
protected getNextFontManifest() { protected getNextFontManifest() {
return undefined return undefined
} }
...@@ -1747,7 +1743,6 @@ export default class DevServer extends Server { ...@@ -1747,7 +1743,6 @@ export default class DevServer extends Server {
// manifest. // manifest.
if (!!this.appDir) { if (!!this.appDir) {
this.clientReferenceManifest = super.getServerComponentManifest() this.clientReferenceManifest = super.getServerComponentManifest()
this.serverCSSManifest = super.getServerCSSManifest()
} }
this.nextFontManifest = super.getNextFontManifest() this.nextFontManifest = super.getNextFontManifest()
// before we re-evaluate a route module, we want to restore globals that might // before we re-evaluate a route module, we want to restore globals that might
......
...@@ -44,7 +44,6 @@ import { ...@@ -44,7 +44,6 @@ import {
CLIENT_REFERENCE_MANIFEST, CLIENT_REFERENCE_MANIFEST,
CLIENT_PUBLIC_FILES_PATH, CLIENT_PUBLIC_FILES_PATH,
APP_PATHS_MANIFEST, APP_PATHS_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
NEXT_FONT_MANIFEST, NEXT_FONT_MANIFEST,
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
...@@ -960,7 +959,6 @@ export default class NextNodeServer extends BaseServer { ...@@ -960,7 +959,6 @@ export default class NextNodeServer extends BaseServer {
// object here but only updating its `clientReferenceManifest` field. // object here but only updating its `clientReferenceManifest` field.
// https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952 // https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952
renderOpts.clientReferenceManifest = this.clientReferenceManifest renderOpts.clientReferenceManifest = this.clientReferenceManifest
renderOpts.serverCSSManifest = this.serverCSSManifest
renderOpts.nextFontManifest = this.nextFontManifest renderOpts.nextFontManifest = this.nextFontManifest
if (this.hasAppDir && renderOpts.isAppPath) { if (this.hasAppDir && renderOpts.isAppPath) {
...@@ -1169,15 +1167,6 @@ export default class NextNodeServer extends BaseServer { ...@@ -1169,15 +1167,6 @@ export default class NextNodeServer extends BaseServer {
)) ))
} }
protected getServerCSSManifest() {
if (!this.hasAppDir) return undefined
return require(join(
this.distDir,
'server',
FLIGHT_SERVER_CSS_MANIFEST + '.json'
))
}
protected getNextFontManifest() { protected getNextFontManifest() {
return require(join(this.distDir, 'server', `${NEXT_FONT_MANIFEST}.json`)) return require(join(this.distDir, 'server', `${NEXT_FONT_MANIFEST}.json`))
} }
......
...@@ -249,7 +249,6 @@ export type RenderOptsPartial = { ...@@ -249,7 +249,6 @@ export type RenderOptsPartial = {
resolvedUrl?: string resolvedUrl?: string
resolvedAsPath?: string resolvedAsPath?: string
clientReferenceManifest?: ClientReferenceManifest clientReferenceManifest?: ClientReferenceManifest
serverCSSManifest?: any
nextFontManifest?: NextFontManifest nextFontManifest?: NextFontManifest
distDir?: string distDir?: string
locale?: string locale?: string
......
...@@ -168,9 +168,6 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -168,9 +168,6 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
return this.serverOptions.webServerConfig.extendRenderOpts return this.serverOptions.webServerConfig.extendRenderOpts
.clientReferenceManifest .clientReferenceManifest
} }
protected getServerCSSManifest() {
return this.serverOptions.webServerConfig.extendRenderOpts.serverCSSManifest
}
protected getNextFontManifest() { protected getNextFontManifest() {
return this.serverOptions.webServerConfig.extendRenderOpts.nextFontManifest return this.serverOptions.webServerConfig.extendRenderOpts.nextFontManifest
......
...@@ -56,8 +56,6 @@ export const NEXT_CLIENT_SSR_ENTRY_SUFFIX = '.__sc_client__' ...@@ -56,8 +56,6 @@ export const NEXT_CLIENT_SSR_ENTRY_SUFFIX = '.__sc_client__'
// server/client-reference-manifest // server/client-reference-manifest
export const CLIENT_REFERENCE_MANIFEST = 'client-reference-manifest' export const CLIENT_REFERENCE_MANIFEST = 'client-reference-manifest'
// server/flight-server-css-manifest
export const FLIGHT_SERVER_CSS_MANIFEST = 'flight-server-css-manifest'
// server/server-reference-manifest // server/server-reference-manifest
export const SERVER_REFERENCE_MANIFEST = 'server-reference-manifest' export const SERVER_REFERENCE_MANIFEST = 'server-reference-manifest'
// server/middleware-build-manifest.js // server/middleware-build-manifest.js
......
...@@ -2,6 +2,20 @@ import { createNextDescribe, FileRef } from 'e2e-utils' ...@@ -2,6 +2,20 @@ import { createNextDescribe, FileRef } from 'e2e-utils'
import { getRedboxSource, hasRedbox } from 'next-test-utils' import { getRedboxSource, hasRedbox } from 'next-test-utils'
import { join } from 'path' import { join } from 'path'
// TODO-APP: due to a current implementation limitation, we don't have proper tree
// shaking when across the server/client boundaries (e.g. all referenced client
// modules by a server module will be included in the bundle even it's not actually
// used by that server module).
// This is a known limitation of flight-client-entry-plugin and we will improve
// this in the future.
// TODO-APP: After the above issue is fixed, we should change this function to
// be strictly equal instead: `expect(arr).toEqual(expected)`.
function containObjects(arr: any[], expected: any[]) {
for (const o of expected) {
expect(arr).toContainEqual(o)
}
}
const getAttrs = (elems: Cheerio) => const getAttrs = (elems: Cheerio) =>
Array.from(elems) Array.from(elems)
.map((elem) => elem.attribs) .map((elem) => elem.attribs)
...@@ -231,8 +245,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { ...@@ -231,8 +245,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => {
expect($('link[rel="preconnect"]').length).toBe(0) expect($('link[rel="preconnect"]').length).toBe(0)
// From root layout // From root layout
expect($('link[as="font"]').length).toBe(3) containObjects(getAttrs($('link[as="font"]')), [
expect(getAttrs($('link[as="font"]'))).toEqual([
{ {
as: 'font', as: 'font',
crossorigin: '', crossorigin: '',
...@@ -264,7 +277,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { ...@@ -264,7 +277,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => {
expect($('link[rel="preconnect"]').length).toBe(0) expect($('link[rel="preconnect"]').length).toBe(0)
// From root layout // From root layout
expect(getAttrs($('link[as="font"]'))).toEqual([ containObjects(getAttrs($('link[as="font"]')), [
{ {
as: 'font', as: 'font',
crossorigin: '', crossorigin: '',
...@@ -296,7 +309,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { ...@@ -296,7 +309,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => {
expect($('link[rel="preconnect"]').length).toBe(0) expect($('link[rel="preconnect"]').length).toBe(0)
// From root layout // From root layout
expect(getAttrs($('link[as="font"]'))).toEqual([ containObjects(getAttrs($('link[as="font"]')), [
{ {
as: 'font', as: 'font',
crossorigin: '', crossorigin: '',
...@@ -321,7 +334,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { ...@@ -321,7 +334,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => {
expect($('link[rel="preconnect"]').length).toBe(0) expect($('link[rel="preconnect"]').length).toBe(0)
// From root layout // From root layout
expect(getAttrs($('link[as="font"]'))).toEqual([ containObjects(getAttrs($('link[as="font"]')), [
{ {
as: 'font', as: 'font',
crossorigin: '', crossorigin: '',
......
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