From 56f26bfcdba7bbc4384f24dc2e960d6e31695e13 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Fri, 9 Jun 2023 11:58:30 +0200 Subject: [PATCH 01/12] simplify things --- .../next-core/js/src/entry/app-renderer.tsx | 38 ++++-- packages/next/src/build/index.ts | 9 -- .../loaders/next-edge-ssr-loader/index.ts | 2 - .../loaders/next-edge-ssr-loader/render.ts | 3 - .../plugins/flight-client-entry-plugin.ts | 122 ------------------ .../webpack/plugins/flight-manifest-plugin.ts | 81 ++++++------ .../webpack/plugins/middleware-plugin.ts | 2 - packages/next/src/export/index.ts | 6 - .../src/server/app-render/action-handler.ts | 12 ++ .../next/src/server/app-render/app-render.tsx | 23 +--- .../app-render/get-css-inlined-link-tags.tsx | 53 ++------ .../app-render/get-preloadable-fonts.tsx | 30 ++--- .../app-render/get-server-css-for-entries.tsx | 18 --- packages/next/src/server/app-render/types.ts | 6 +- packages/next/src/server/base-server.ts | 6 - .../next/src/server/dev/next-dev-server.ts | 5 - packages/next/src/server/next-server.ts | 11 -- packages/next/src/server/render.tsx | 1 - packages/next/src/server/web-server.ts | 3 - packages/next/src/shared/lib/constants.ts | 2 - 20 files changed, 111 insertions(+), 322 deletions(-) delete mode 100644 packages/next/src/server/app-render/get-server-css-for-entries.tsx diff --git a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx index c9fdc523d2c6b..badd01493a9c2 100644 --- a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx +++ b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx @@ -16,10 +16,7 @@ declare global { import type { Ipc } from '@vercel/turbopack-node/ipc/index' import type { IncomingMessage } from 'node:http' -import type { - ClientCSSReferenceManifest, - ClientReferenceManifest, -} from 'next/dist/build/webpack/plugins/flight-manifest-plugin' +import type { ClientReferenceManifest } from 'next/dist/build/webpack/plugins/flight-manifest-plugin' import type { RenderData } from 'types/turbopack' import type { RenderOpts } from 'next/dist/server/app-render/types' @@ -138,11 +135,27 @@ async function runOperation(renderData: RenderData) { } } + const proxyMethodsForEntryCSS: ProxyHandler< + ClientReferenceManifest['entryCSSFiles'] + > = { + get(_target, 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 proxyMethodsNested = ( - type: 'ssrModuleMapping' | 'clientModules' + type: 'ssrModuleMapping' | 'clientModules' | 'entryCSSFiles' ): ProxyHandler< | ClientReferenceManifest['ssrModuleMapping'] | ClientReferenceManifest['clientModules'] + | ClientReferenceManifest['entryCSSFiles'] > => { return { get(_target, key: string) { @@ -170,6 +183,9 @@ async function runOperation(renderData: RenderData) { chunks: JSON.parse(id)[1], } } + if (type === 'entryCSSFiles') { + return new Proxy({}, proxyMethodsForEntryCSS) + } }, } } @@ -183,6 +199,10 @@ async function runOperation(renderData: RenderData) { {}, proxyMethodsNested('ssrModuleMapping') ) + const entryCSSFilesProxy = new Proxy( + {}, + proxyMethodsNested('entryCSSFiles') + ) return { get(_target: any, prop: string) { if (prop === 'ssrModuleMapping') { @@ -191,6 +211,9 @@ async function runOperation(renderData: RenderData) { if (prop === 'clientModules') { return clientModulesProxy } + if (prop === 'entryCSSFiles') { + return entryCSSFilesProxy + } }, } } @@ -230,10 +253,6 @@ async function runOperation(renderData: RenderData) { } const manifest: ClientReferenceManifest = new Proxy({} as any, proxyMethods()) - const serverCSSManifest: ClientCSSReferenceManifest = { - cssImports: new Proxy({} as any, cssImportProxyMethods), - cssModules: {}, - } const req: IncomingMessage = { url: renderData.originalUrl, method: renderData.method, @@ -271,7 +290,6 @@ async function runOperation(renderData: RenderData) { pages: ['page.js'], }, clientReferenceManifest: manifest, - serverCSSManifest, runtime: 'nodejs', serverComponents: true, assetPrefix: '', diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index ba1fd3843e828..9c6c546ab5958 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -62,7 +62,6 @@ import { APP_PATHS_MANIFEST, APP_PATH_ROUTES_MANIFEST, APP_BUILD_MANIFEST, - FLIGHT_SERVER_CSS_MANIFEST, RSC_MODULE_TYPES, NEXT_FONT_MANIFEST, SUBRESOURCE_INTEGRITY_MANIFEST, @@ -893,14 +892,6 @@ export default async function build( SERVER_DIRECTORY, CLIENT_REFERENCE_MANIFEST + '.json' ), - path.join( - SERVER_DIRECTORY, - FLIGHT_SERVER_CSS_MANIFEST + '.js' - ), - path.join( - SERVER_DIRECTORY, - FLIGHT_SERVER_CSS_MANIFEST + '.json' - ), path.join( SERVER_DIRECTORY, SERVER_REFERENCE_MANIFEST + '.js' diff --git a/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts b/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts index 792f04e1c6475..25e3128d77560 100644 --- a/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts +++ b/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts @@ -141,7 +141,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction = const prerenderManifest = self.__PRERENDER_MANIFEST const reactLoadableManifest = self.__REACT_LOADABLE_MANIFEST const rscManifest = self.__RSC_MANIFEST - const rscCssManifest = self.__RSC_CSS_MANIFEST const rscServerManifest = self.__RSC_SERVER_MANIFEST const subresourceIntegrityManifest = ${ sriEnabled ? 'self.__SUBRESOURCE_INTEGRITY_MANIFEST' : 'undefined' @@ -164,7 +163,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction = pagesRenderToHTML, reactLoadableManifest, clientReferenceManifest: ${isServerComponent} ? rscManifest : null, - serverCSSManifest: ${isServerComponent} ? rscCssManifest : null, serverActionsManifest: ${isServerComponent} ? rscServerManifest : null, subresourceIntegrityManifest, config: ${stringifiedConfig}, diff --git a/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/render.ts b/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/render.ts index 9e4371e1ee57e..a120b65022471 100644 --- a/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/render.ts +++ b/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/render.ts @@ -31,7 +31,6 @@ export function getRender({ pagesRenderToHTML, clientReferenceManifest, subresourceIntegrityManifest, - serverCSSManifest, serverActionsManifest, config, buildId, @@ -53,7 +52,6 @@ export function getRender({ reactLoadableManifest: ReactLoadableManifest subresourceIntegrityManifest?: Record clientReferenceManifest?: ClientReferenceManifest - serverCSSManifest: any serverActionsManifest: any appServerMod: any config: NextConfigComplete @@ -88,7 +86,6 @@ export function getRender({ supportsDynamicHTML: true, disableOptimizedLoading: true, clientReferenceManifest, - serverCSSManifest, serverActionsManifest, }, appRenderToHTML, diff --git a/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts b/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts index ee89870af8c06..e37ba12700a1b 100644 --- a/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts +++ b/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts @@ -3,7 +3,6 @@ import type { ClientComponentImports, NextFlightClientEntryLoaderOptions, } from '../loaders/next-flight-client-entry-loader' -import type { ClientCSSReferenceManifest } from './flight-manifest-plugin' import { webpack } from 'next/dist/compiled/webpack/webpack' import { stringify } from 'querystring' @@ -21,7 +20,6 @@ import { COMPILER_NAMES, EDGE_RUNTIME_WEBPACK, SERVER_REFERENCE_MANIFEST, - FLIGHT_SERVER_CSS_MANIFEST, } from '../../../shared/lib/constants' import { generateActionId, @@ -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. serverModuleIds: {} as Record, edgeServerModuleIds: {} as Record, @@ -308,7 +302,6 @@ export class ClientReferenceEntryPlugin { compilation, entryName: name, clientComponentImports, - cssImports, bundlePath, absolutePagePath: entryRequest, }) @@ -475,121 +468,6 @@ export class ClientReferenceEntryPlugin { 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> = {} - - 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 - 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 = - cssManifest.cssModules || {} - entryCSSInfo[entryName] = [...cssImportsForChunk[entryName]] - - cssManifest.cssModules = entryCSSInfo - }) - }) - - forEachEntryModule(compilation, ({ name, entryModule }) => { - const clientEntryDependencyMap = collectClientEntryDependencyMap(name) - const tracked = new Set() - 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=' + manifest - ) as unknown as webpack.sources.RawSource - } - ) - // Invalidate in development to trigger recompilation const invalidator = getInvalidator(compiler.outputPath) // Check if any of the entry injections need an invalidation diff --git a/packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts b/packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts index fb43ad16e5338..13bec4dd85782 100644 --- a/packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts +++ b/packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts @@ -69,14 +69,11 @@ export type ClientReferenceManifest = { edgeSSRModuleMapping: { [moduleId: string]: ManifestNode } -} - -export type ClientCSSReferenceManifest = { - cssImports: { - [modulePath: string]: string[] - } - cssModules?: { - [entry: string]: string[] + entryCSSFiles: { + [entry: string]: { + modules: string[] + files: string[] + } } } @@ -85,11 +82,13 @@ const PLUGIN_NAME = 'ClientReferenceManifestPlugin' export class ClientReferenceManifestPlugin { dev: Options['dev'] = false appDir: Options['appDir'] + appDirBase: string ASYNC_CLIENT_MODULES: Set 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) } @@ -130,6 +129,7 @@ export class ClientReferenceManifestPlugin { ssrModuleMapping: {}, edgeSSRModuleMapping: {}, clientModules: {}, + entryCSSFiles: {}, } const clientRequestsSet = new Set() @@ -172,11 +172,24 @@ export class ClientReferenceManifestPlugin { } const requiredChunks = getAppPathRequiredChunks() - const recordModule = ( - id: ModuleId, - mod: webpack.NormalModule, - chunkCSS: string[] - ) => { + let chunkEntryName: string | null = null + if (chunkGroup.name && /^app[\\/]/.test(chunkGroup.name)) { + // Absolute path without the extension + 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) // Skip all modules from the pages folder. CSS modules are a special case @@ -196,6 +209,13 @@ export class ClientReferenceManifestPlugin { return } + if (isCSSModule) { + if (chunkEntryName) { + manifest.entryCSSFiles[chunkEntryName].modules.push(resource) + } + return + } + const moduleReferences = manifest.clientModules const moduleIdMapping = manifest.ssrModuleMapping const edgeModuleIdMapping = manifest.edgeSSRModuleMapping @@ -211,26 +231,6 @@ export class ClientReferenceManifestPlugin { if (!ssrNamedModuleId.startsWith('.')) 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, // or if the module is marked as client module. if ( @@ -369,25 +369,28 @@ export class ClientReferenceManifestPlugin { // TODO: Update type so that it doesn't have to be cast. ) as Iterable - const chunkCSS = [...chunk.files].filter( - (f) => !f.startsWith('static/css/pages/') && f.endsWith('.css') - ) - for (const mod of chunkModules) { 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. // TODO: remove any const anyModule = mod as any if (anyModule.modules) { 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 diff --git a/packages/next/src/build/webpack/plugins/middleware-plugin.ts b/packages/next/src/build/webpack/plugins/middleware-plugin.ts index a06c388fe40af..a496f53295467 100644 --- a/packages/next/src/build/webpack/plugins/middleware-plugin.ts +++ b/packages/next/src/build/webpack/plugins/middleware-plugin.ts @@ -17,7 +17,6 @@ import { MIDDLEWARE_MANIFEST, MIDDLEWARE_REACT_LOADABLE_MANIFEST, NEXT_CLIENT_SSR_ENTRY_SUFFIX, - FLIGHT_SERVER_CSS_MANIFEST, SUBRESOURCE_INTEGRITY_MANIFEST, NEXT_FONT_MANIFEST, SERVER_REFERENCE_MANIFEST, @@ -100,7 +99,6 @@ function getEntryFiles( if (meta.edgeSSR.isServerComponent) { files.push(`server/${SERVER_REFERENCE_MANIFEST}.js`) files.push(`server/${CLIENT_REFERENCE_MANIFEST}.js`) - files.push(`server/${FLIGHT_SERVER_CSS_MANIFEST}.js`) if (opts.sriEnabled) { files.push(`server/${SUBRESOURCE_INTEGRITY_MANIFEST}.js`) } diff --git a/packages/next/src/export/index.ts b/packages/next/src/export/index.ts index 6c6fd3a85e458..89d76128516e4 100644 --- a/packages/next/src/export/index.ts +++ b/packages/next/src/export/index.ts @@ -25,7 +25,6 @@ import { EXPORT_DETAIL, EXPORT_MARKER, CLIENT_REFERENCE_MANIFEST, - FLIGHT_SERVER_CSS_MANIFEST, NEXT_FONT_MANIFEST, MIDDLEWARE_MANIFEST, PAGES_MANIFEST, @@ -480,11 +479,6 @@ export default async function exportApp( SERVER_DIRECTORY, CLIENT_REFERENCE_MANIFEST + '.json' )), - serverCSSManifest: require(join( - distDir, - SERVER_DIRECTORY, - FLIGHT_SERVER_CSS_MANIFEST + '.json' - )), serverActionsManifest: require(join( distDir, SERVER_DIRECTORY, diff --git a/packages/next/src/server/app-render/action-handler.ts b/packages/next/src/server/app-render/action-handler.ts index 26b807a22de6a..b9b748ad706fe 100644 --- a/packages/next/src/server/app-render/action-handler.ts +++ b/packages/next/src/server/app-render/action-handler.ts @@ -363,6 +363,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 = serverActionsManifest[ process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node' diff --git a/packages/next/src/server/app-render/app-render.tsx b/packages/next/src/server/app-render/app-render.tsx index a50cb0f3c101e..4745bfe8092ed 100644 --- a/packages/next/src/server/app-render/app-render.tsx +++ b/packages/next/src/server/app-render/app-render.tsx @@ -59,7 +59,6 @@ import { createErrorHandler } from './create-error-handler' import { getShortDynamicParamType } from './get-short-dynamic-param-type' import { getSegmentParam } from './get-segment-param' import { getCssInlinedLinkTags } from './get-css-inlined-link-tags' -import { getServerCSSForEntries } from './get-server-css-for-entries' import { getPreloadableFonts } from './get-preloadable-fonts' import { getScriptNonceFromHeader } from './get-script-nonce-from-header' import { renderToString } from './render-to-string' @@ -162,7 +161,6 @@ export async function renderToHTMLOrFlight( const appUsingSizeAdjust = nextFontManifest?.appUsingSizeAdjust const clientReferenceManifest = renderOpts.clientReferenceManifest! - const serverCSSManifest = renderOpts.serverCSSManifest! const capturedErrors: Error[] = [] const allCapturedErrors: Error[] = [] @@ -351,15 +349,6 @@ export async function renderToHTMLOrFlight( 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 getAssetQueryString = (addTimestamp: boolean) => { @@ -389,9 +378,7 @@ export async function renderToHTMLOrFlight( }): Promise => { const cssHrefs = getCssInlinedLinkTags( clientReferenceManifest, - serverCSSManifest!, filePath, - serverCSSForEntries, injectedCSS ) @@ -448,9 +435,7 @@ export async function renderToHTMLOrFlight( const stylesheets: string[] = layoutOrPagePath ? getCssInlinedLinkTags( clientReferenceManifest, - serverCSSManifest!, layoutOrPagePath, - serverCSSForEntries, injectedCSSWithCurrentLayout, true ) @@ -458,9 +443,8 @@ export async function renderToHTMLOrFlight( const preloadedFontFiles = layoutOrPagePath ? getPreloadableFonts( - serverCSSManifest!, + clientReferenceManifest, nextFontManifest, - serverCSSForEntries, layoutOrPagePath, injectedFontPreloadTagsWithCurrentLayout ) @@ -1107,16 +1091,13 @@ export async function renderToHTMLOrFlight( if (layoutPath) { getCssInlinedLinkTags( clientReferenceManifest, - serverCSSManifest!, layoutPath, - serverCSSForEntries, injectedCSSWithCurrentLayout, true ) getPreloadableFonts( - serverCSSManifest!, + clientReferenceManifest, nextFontManifest, - serverCSSForEntries, layoutPath, injectedFontPreloadTagsWithCurrentLayout ) diff --git a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx index d11751878cf0f..a28cc8f2713c5 100644 --- a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx +++ b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx @@ -1,7 +1,5 @@ -import { - ClientCSSReferenceManifest, - ClientReferenceManifest, -} from '../../build/webpack/plugins/flight-manifest-plugin' +import { parse, sep } from 'node:path' +import { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' import { getClientReferenceModuleKey } from '../../lib/client-reference' /** @@ -9,51 +7,24 @@ import { getClientReferenceModuleKey } from '../../lib/client-reference' */ export function getCssInlinedLinkTags( clientReferenceManifest: ClientReferenceManifest, - serverCSSManifest: ClientCSSReferenceManifest, filePath: string, - serverCSSForEntries: string[], injectedCSS: Set, collectNewCSSImports?: boolean ): string[] { - const layoutOrPageCssModules = serverCSSManifest.cssImports[filePath] + const parsedFilepath = parse(filePath) + const filePathWithoutExt = parsedFilepath.dir + sep + parsedFilepath.name - const filePathWithoutExt = filePath.replace(/(\.[A-Za-z0-9]+)+$/, '') - - if (!layoutOrPageCssModules) { - return [] - } const chunks = new Set() - const isNotFoundPage = /(\/|\\)not-found/.test(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 the CSS is already injected by a parent layer, we don't need - // to inject it again. - if (!injectedCSS.has(mod)) { - const modData = - 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) - } - } + const entryCSSFiles = + clientReferenceManifest.entryCSSFiles[filePathWithoutExt] + if (entryCSSFiles) { + for (const file of entryCSSFiles.files) { + if (!injectedCSS.has(file)) { + if (collectNewCSSImports) { + injectedCSS.add(file) } + chunks.add(file) } } } diff --git a/packages/next/src/server/app-render/get-preloadable-fonts.tsx b/packages/next/src/server/app-render/get-preloadable-fonts.tsx index 9fcef03af032f..f4949b7a41c86 100644 --- a/packages/next/src/server/app-render/get-preloadable-fonts.tsx +++ b/packages/next/src/server/app-render/get-preloadable-fonts.tsx @@ -1,5 +1,5 @@ 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 @@ -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 */ export function getPreloadableFonts( - serverCSSManifest: ClientCSSReferenceManifest, + clientReferenceManifest: ClientReferenceManifest, nextFontManifest: NextFontManifest | undefined, - serverCSSForEntries: string[], filePath: string | undefined, injectedFontPreloadTags: Set ): string[] | null { if (!nextFontManifest || !filePath) { return null } - const layoutOrPageCss = serverCSSManifest.cssImports[filePath] + const filepathWithoutExtension = filePath.replace(/\.[^.]+$/, '') + const entryCSS = + clientReferenceManifest.entryCSSFiles[filepathWithoutExtension] - if (!layoutOrPageCss) { + if (!entryCSS) { return null } const fontFiles = new Set() let foundFontUsage = false - for (const css of layoutOrPageCss) { - // We only include the CSS if it is used by this entrypoint. - if (serverCSSForEntries.includes(css)) { - const preloadedFontFiles = nextFontManifest.app[css] - if (preloadedFontFiles) { - foundFontUsage = true - for (const fontFile of preloadedFontFiles) { - if (!injectedFontPreloadTags.has(fontFile)) { - fontFiles.add(fontFile) - injectedFontPreloadTags.add(fontFile) - } + for (const cssModules of entryCSS.modules) { + const preloadedFontFiles = nextFontManifest.app[cssModules] + if (preloadedFontFiles) { + foundFontUsage = true + for (const fontFile of preloadedFontFiles) { + if (!injectedFontPreloadTags.has(fontFile)) { + fontFiles.add(fontFile) + injectedFontPreloadTags.add(fontFile) } } } diff --git a/packages/next/src/server/app-render/get-server-css-for-entries.tsx b/packages/next/src/server/app-render/get-server-css-for-entries.tsx deleted file mode 100644 index e5f23063b1404..0000000000000 --- a/packages/next/src/server/app-render/get-server-css-for-entries.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 -} diff --git a/packages/next/src/server/app-render/types.ts b/packages/next/src/server/app-render/types.ts index e5f209876638f..a09f288f45ab5 100644 --- a/packages/next/src/server/app-render/types.ts +++ b/packages/next/src/server/app-render/types.ts @@ -1,9 +1,6 @@ import type { LoadComponentsReturnType } from '../load-components' import type { ServerRuntime } from '../../../types' -import type { - ClientCSSReferenceManifest, - ClientReferenceManifest, -} from '../../build/webpack/plugins/flight-manifest-plugin' +import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import zod from 'zod' @@ -119,7 +116,6 @@ export type RenderOptsPartial = { err?: Error | null dev?: boolean clientReferenceManifest?: ClientReferenceManifest - serverCSSManifest?: ClientCSSReferenceManifest supportsDynamicHTML: boolean runtime?: ServerRuntime serverComponents?: boolean diff --git a/packages/next/src/server/base-server.ts b/packages/next/src/server/base-server.ts index 420798df42f02..7b3e7480a5a38 100644 --- a/packages/next/src/server/base-server.ts +++ b/packages/next/src/server/base-server.ts @@ -249,7 +249,6 @@ export default abstract class Server { supportsDynamicHTML?: boolean isBot?: boolean clientReferenceManifest?: ClientReferenceManifest - serverCSSManifest?: any serverActionsManifest?: any nextFontManifest?: NextFontManifest renderServerComponentData?: boolean @@ -264,7 +263,6 @@ export default abstract class Server { protected appPathRoutes?: Record protected customRoutes: CustomRoutes protected clientReferenceManifest?: ClientReferenceManifest - protected serverCSSManifest?: any protected nextFontManifest?: NextFontManifest public readonly hostname?: string public readonly port?: number @@ -289,7 +287,6 @@ export default abstract class Server { protected abstract getFontManifest(): FontManifest | undefined protected abstract getPrerenderManifest(): PrerenderManifest protected abstract getServerComponentManifest(): any - protected abstract getServerCSSManifest(): any protected abstract getNextFontManifest(): NextFontManifest | undefined protected abstract attachRequestMeta( req: BaseNextRequest, @@ -417,9 +414,6 @@ export default abstract class Server { this.clientReferenceManifest = serverComponents ? this.getServerComponentManifest() : undefined - this.serverCSSManifest = serverComponents - ? this.getServerCSSManifest() - : undefined this.nextFontManifest = this.getNextFontManifest() if (process.env.NEXT_RUNTIME !== 'edge') { diff --git a/packages/next/src/server/dev/next-dev-server.ts b/packages/next/src/server/dev/next-dev-server.ts index 58b5430840b56..44309dd602778 100644 --- a/packages/next/src/server/dev/next-dev-server.ts +++ b/packages/next/src/server/dev/next-dev-server.ts @@ -1464,10 +1464,6 @@ export default class DevServer extends Server { return undefined } - protected getServerCSSManifest() { - return undefined - } - protected getNextFontManifest() { return undefined } @@ -1781,7 +1777,6 @@ export default class DevServer extends Server { // manifest. if (!!this.appDir) { this.clientReferenceManifest = super.getServerComponentManifest() - this.serverCSSManifest = super.getServerCSSManifest() } this.nextFontManifest = super.getNextFontManifest() // before we re-evaluate a route module, we want to restore globals that might diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts index 67b9b5bbb8baf..3675d3937cd0d 100644 --- a/packages/next/src/server/next-server.ts +++ b/packages/next/src/server/next-server.ts @@ -44,7 +44,6 @@ import { CLIENT_REFERENCE_MANIFEST, CLIENT_PUBLIC_FILES_PATH, APP_PATHS_MANIFEST, - FLIGHT_SERVER_CSS_MANIFEST, SERVER_DIRECTORY, NEXT_FONT_MANIFEST, PHASE_PRODUCTION_BUILD, @@ -959,7 +958,6 @@ export default class NextNodeServer extends BaseServer { // object here but only updating its `clientReferenceManifest` field. // https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952 renderOpts.clientReferenceManifest = this.clientReferenceManifest - renderOpts.serverCSSManifest = this.serverCSSManifest renderOpts.nextFontManifest = this.nextFontManifest if (this.hasAppDir && renderOpts.isAppPath) { @@ -1168,15 +1166,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() { return require(join(this.distDir, 'server', `${NEXT_FONT_MANIFEST}.json`)) } diff --git a/packages/next/src/server/render.tsx b/packages/next/src/server/render.tsx index c14328438c3e0..72d2705f2643f 100644 --- a/packages/next/src/server/render.tsx +++ b/packages/next/src/server/render.tsx @@ -250,7 +250,6 @@ export type RenderOptsPartial = { resolvedUrl?: string resolvedAsPath?: string clientReferenceManifest?: ClientReferenceManifest - serverCSSManifest?: any nextFontManifest?: NextFontManifest distDir?: string locale?: string diff --git a/packages/next/src/server/web-server.ts b/packages/next/src/server/web-server.ts index 1ff5fb3d6f595..2c1f80e3221c7 100644 --- a/packages/next/src/server/web-server.ts +++ b/packages/next/src/server/web-server.ts @@ -168,9 +168,6 @@ export default class NextWebServer extends BaseServer { return this.serverOptions.webServerConfig.extendRenderOpts .clientReferenceManifest } - protected getServerCSSManifest() { - return this.serverOptions.webServerConfig.extendRenderOpts.serverCSSManifest - } protected getNextFontManifest() { return this.serverOptions.webServerConfig.extendRenderOpts.nextFontManifest diff --git a/packages/next/src/shared/lib/constants.ts b/packages/next/src/shared/lib/constants.ts index 82845e267d88f..fa1fcd0e74507 100644 --- a/packages/next/src/shared/lib/constants.ts +++ b/packages/next/src/shared/lib/constants.ts @@ -56,8 +56,6 @@ export const NEXT_CLIENT_SSR_ENTRY_SUFFIX = '.__sc_client__' // server/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 export const SERVER_REFERENCE_MANIFEST = 'server-reference-manifest' // server/middleware-build-manifest.js From f90f29a12c329895ef86be58c3030219e43e82b4 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Fri, 9 Jun 2023 12:22:15 +0200 Subject: [PATCH 02/12] fix --- .../src/server/app-render/get-css-inlined-link-tags.tsx | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx index a28cc8f2713c5..2fb4016598e54 100644 --- a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx +++ b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx @@ -1,6 +1,4 @@ -import { parse, sep } from 'node:path' import { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' -import { getClientReferenceModuleKey } from '../../lib/client-reference' /** * Get external stylesheet link hrefs based on server CSS manifest. @@ -11,9 +9,7 @@ export function getCssInlinedLinkTags( injectedCSS: Set, collectNewCSSImports?: boolean ): string[] { - const parsedFilepath = parse(filePath) - const filePathWithoutExt = parsedFilepath.dir + sep + parsedFilepath.name - + const filePathWithoutExt = filePath.replace(/\.[^.]+$/, '') const chunks = new Set() const entryCSSFiles = From 207f2ac4b11a5bd101d548d6ab7ae257dcd84aac Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Fri, 9 Jun 2023 16:17:52 +0200 Subject: [PATCH 03/12] skip tree-shaking test for next-font --- test/e2e/app-dir/next-font/next-font.test.ts | 23 +++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/test/e2e/app-dir/next-font/next-font.test.ts b/test/e2e/app-dir/next-font/next-font.test.ts index b80e98f08b741..4320d6b556eac 100644 --- a/test/e2e/app-dir/next-font/next-font.test.ts +++ b/test/e2e/app-dir/next-font/next-font.test.ts @@ -2,6 +2,20 @@ import { createNextDescribe, FileRef } from 'e2e-utils' import { getRedboxSource, hasRedbox } from 'next-test-utils' 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) => Array.from(elems) .map((elem) => elem.attribs) @@ -231,8 +245,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { expect($('link[rel="preconnect"]').length).toBe(0) // From root layout - expect($('link[as="font"]').length).toBe(3) - expect(getAttrs($('link[as="font"]'))).toEqual([ + containObjects(getAttrs($('link[as="font"]')), [ { as: 'font', crossorigin: '', @@ -264,7 +277,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { expect($('link[rel="preconnect"]').length).toBe(0) // From root layout - expect(getAttrs($('link[as="font"]'))).toEqual([ + containObjects(getAttrs($('link[as="font"]')), [ { as: 'font', crossorigin: '', @@ -296,7 +309,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { expect($('link[rel="preconnect"]').length).toBe(0) // From root layout - expect(getAttrs($('link[as="font"]'))).toEqual([ + containObjects(getAttrs($('link[as="font"]')), [ { as: 'font', crossorigin: '', @@ -321,7 +334,7 @@ describe.each([['app'], ['app-old']])('%s', (fixture: string) => { expect($('link[rel="preconnect"]').length).toBe(0) // From root layout - expect(getAttrs($('link[as="font"]'))).toEqual([ + containObjects(getAttrs($('link[as="font"]')), [ { as: 'font', crossorigin: '', From 3a4e21a54cf618d2e55fa3b11925484b51e49d46 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Fri, 9 Jun 2023 16:26:38 +0200 Subject: [PATCH 04/12] fix turbopack proxy --- .../crates/next-core/js/src/entry/app-renderer.tsx | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx index badd01493a9c2..f9ad3e7cae5e2 100644 --- a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx +++ b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx @@ -143,10 +143,13 @@ async function runOperation(renderData: RenderData) { // 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]])) + return { + modules: [], + files: cssChunks + .filter(filterAvailable) + .map(toPath) + .map((chunk: string) => JSON.stringify([chunk, [chunk]])), + } }, } From c8fae60b74e94a1cd0748362b2327c354a41eefb Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Fri, 9 Jun 2023 22:52:25 +0200 Subject: [PATCH 05/12] add error log --- .../next-core/js/src/entry/app-renderer.tsx | 38 +++++++++---------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx index f9ad3e7cae5e2..2b8559d7e0d3d 100644 --- a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx +++ b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx @@ -139,16 +139,24 @@ async function runOperation(renderData: RenderData) { ClientReferenceManifest['entryCSSFiles'] > = { get(_target, prop: string) { - const cssChunks = JSON.parse(prop.replace(/\.js$/, '')) - // TODO(WEB-856) subscribe to changes + try { + const cssChunks = JSON.parse(prop.replace(/\.js$/, '')) + // TODO(WEB-856) subscribe to changes - // This return value is passed to proxyMethodsNested for clientModules - return { - modules: [], - files: cssChunks - .filter(filterAvailable) - .map(toPath) - .map((chunk: string) => JSON.stringify([chunk, [chunk]])), + // This return value is passed to proxyMethodsNested for clientModules + return { + modules: [], + files: cssChunks + .filter(filterAvailable) + .map(toPath) + .map((chunk: string) => JSON.stringify([chunk, [chunk]])), + } + } catch (err) { + console.error('Failed to parse CSS chunks:', err, '\nProp:', prop) + return { + modules: [], + files: [], + } } }, } @@ -242,18 +250,6 @@ async function runOperation(renderData: RenderData) { 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 req: IncomingMessage = { From ac01d248ddaa8f855e24ea465775b799dc7d17fa Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Fri, 9 Jun 2023 23:12:24 +0200 Subject: [PATCH 06/12] fix --- .../next/src/server/app-render/get-css-inlined-link-tags.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx index 2fb4016598e54..0f59bb2a4988c 100644 --- a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx +++ b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx @@ -14,7 +14,7 @@ export function getCssInlinedLinkTags( const entryCSSFiles = clientReferenceManifest.entryCSSFiles[filePathWithoutExt] - if (entryCSSFiles) { + if (Array.isArray(entryCSSFiles)) { for (const file of entryCSSFiles.files) { if (!injectedCSS.has(file)) { if (collectNewCSSImports) { From 88bd075975183cb92b8c29926e5ceae7abf2d351 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Wed, 14 Jun 2023 21:33:02 +0200 Subject: [PATCH 07/12] Revert "fix" This reverts commit ac01d248ddaa8f855e24ea465775b799dc7d17fa. --- .../next/src/server/app-render/get-css-inlined-link-tags.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx index 0f59bb2a4988c..2fb4016598e54 100644 --- a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx +++ b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx @@ -14,7 +14,7 @@ export function getCssInlinedLinkTags( const entryCSSFiles = clientReferenceManifest.entryCSSFiles[filePathWithoutExt] - if (Array.isArray(entryCSSFiles)) { + if (entryCSSFiles) { for (const file of entryCSSFiles.files) { if (!injectedCSS.has(file)) { if (collectNewCSSImports) { From 3ce1fd1035026885dbdb64d31719768d315f086f Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Wed, 14 Jun 2023 21:52:59 +0200 Subject: [PATCH 08/12] fix lint error --- .../next/src/build/webpack/plugins/flight-manifest-plugin.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts b/packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts index 27ec8e978edb0..0f54539b8d01a 100644 --- a/packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts +++ b/packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts @@ -18,7 +18,6 @@ import { getProxiedPluginState } from '../../build-context' import { traverseModules } from '../utils' import { nonNullable } from '../../../lib/non-nullable' import { WEBPACK_LAYERS } from '../../../lib/constants' -import { getClientReferenceModuleKey } from '../../../lib/client-reference' interface Options { dev: boolean From 110c84555848640cc0935bc82919b84adad55e15 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Wed, 14 Jun 2023 22:42:43 +0200 Subject: [PATCH 09/12] test --- .../crates/next-core/js/src/entry/app-renderer.tsx | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx index e8383bcbd58da..721bd70460447 100644 --- a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx +++ b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx @@ -140,16 +140,13 @@ async function runOperation(renderData: RenderData) { > = { get(_target, prop: string) { try { - const cssChunks = JSON.parse(prop.replace(/\.js$/, '')) + const cssChunks = JSON.parse(prop) // TODO(WEB-856) subscribe to changes // This return value is passed to proxyMethodsNested for clientModules return { modules: [], - files: cssChunks - .filter(filterAvailable) - .map(toPath) - .map((chunk: string) => JSON.stringify([chunk, [chunk]])), + files: cssChunks.filter(filterAvailable).map(toPath), } } catch (err) { console.error('Failed to parse CSS chunks:', err, '\nProp:', prop) From 571b10aa77d6026eda5cc2493e8ad21eae8bca41 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Wed, 14 Jun 2023 23:02:18 +0200 Subject: [PATCH 10/12] fix proxy --- .../next-core/js/src/entry/app-renderer.tsx | 40 ++++++++----------- .../app-render/get-css-inlined-link-tags.tsx | 1 + 2 files changed, 17 insertions(+), 24 deletions(-) diff --git a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx index 721bd70460447..f36028d526a5a 100644 --- a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx +++ b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx @@ -135,29 +135,6 @@ async function runOperation(renderData: RenderData) { } } - const proxyMethodsForEntryCSS: ProxyHandler< - ClientReferenceManifest['entryCSSFiles'] - > = { - get(_target, prop: string) { - try { - const cssChunks = JSON.parse(prop) - // TODO(WEB-856) subscribe to changes - - // This return value is passed to proxyMethodsNested for clientModules - return { - modules: [], - files: cssChunks.filter(filterAvailable).map(toPath), - } - } catch (err) { - console.error('Failed to parse CSS chunks:', err, '\nProp:', prop) - return { - modules: [], - files: [], - } - } - }, - } - const proxyMethodsNested = ( type: 'ssrModuleMapping' | 'clientModules' | 'entryCSSFiles' ): ProxyHandler< @@ -192,7 +169,22 @@ async function runOperation(renderData: RenderData) { } } if (type === 'entryCSSFiles') { - return new Proxy({}, proxyMethodsForEntryCSS) + try { + const cssChunks = JSON.parse(key) + // TODO(WEB-856) subscribe to changes + + // This return value is passed to proxyMethodsNested for clientModules + return { + modules: [], + files: cssChunks.filter(filterAvailable).map(toPath), + } + } catch (err) { + console.error('Failed to parse CSS chunks:', err, '\nProp:', key) + return { + modules: [], + files: [], + } + } } }, } diff --git a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx index 2fb4016598e54..7a82bb2400908 100644 --- a/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx +++ b/packages/next/src/server/app-render/get-css-inlined-link-tags.tsx @@ -14,6 +14,7 @@ export function getCssInlinedLinkTags( const entryCSSFiles = clientReferenceManifest.entryCSSFiles[filePathWithoutExt] + if (entryCSSFiles) { for (const file of entryCSSFiles.files) { if (!injectedCSS.has(file)) { From 113a86982caedf6cbf8d9ae33ee6d81a88b665ed Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Wed, 14 Jun 2023 23:02:40 +0200 Subject: [PATCH 11/12] remove try-catch --- .../next-core/js/src/entry/app-renderer.tsx | 20 ++++++------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx index f36028d526a5a..d1195b59562cd 100644 --- a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx +++ b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx @@ -169,21 +169,13 @@ async function runOperation(renderData: RenderData) { } } if (type === 'entryCSSFiles') { - try { - const cssChunks = JSON.parse(key) - // TODO(WEB-856) subscribe to changes + const cssChunks = JSON.parse(key) + // TODO(WEB-856) subscribe to changes - // This return value is passed to proxyMethodsNested for clientModules - return { - modules: [], - files: cssChunks.filter(filterAvailable).map(toPath), - } - } catch (err) { - console.error('Failed to parse CSS chunks:', err, '\nProp:', key) - return { - modules: [], - files: [], - } + // This return value is passed to proxyMethodsNested for clientModules + return { + modules: [], + files: cssChunks.filter(filterAvailable).map(toPath), } } }, From 9a8c8eb7ba10ba74b6b5c6298837d6f1f228fa02 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Wed, 14 Jun 2023 23:02:53 +0200 Subject: [PATCH 12/12] remove comment --- .../next-swc/crates/next-core/js/src/entry/app-renderer.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx index d1195b59562cd..6ee374288b570 100644 --- a/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx +++ b/packages/next-swc/crates/next-core/js/src/entry/app-renderer.tsx @@ -171,8 +171,6 @@ async function runOperation(renderData: RenderData) { if (type === 'entryCSSFiles') { const cssChunks = JSON.parse(key) // TODO(WEB-856) subscribe to changes - - // This return value is passed to proxyMethodsNested for clientModules return { modules: [], files: cssChunks.filter(filterAvailable).map(toPath),