Unverified Commit 3a9bfe60 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Fix CSS imports being tracked multiple times (#44938)

Currently the way our renderer injects CSS is to first track CSS imports on the module level, and then render these links on each layer. However, in a complex application it's possible that one CSS being imported in many modules, and in multiple layouts. This causes an issue of duplication. And if there are many rules the order could be messed up by that. 

This PR deduplicates CSS resources used by one entry (layout, page, error, ...) and all its parent layouts. If an entry is rendered, all its ancestors are rendered too.

See test case for more details. Currently those two tests will all fail.

Fixes #42862.

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent b04fc99e
...@@ -49,7 +49,9 @@ async function createTreeCodeFromPath({ ...@@ -49,7 +49,9 @@ async function createTreeCodeFromPath({
async function createSubtreePropsFromSegmentPath( async function createSubtreePropsFromSegmentPath(
segments: string[] segments: string[]
): Promise<string> { ): Promise<{
treeCode: string
}> {
const segmentPath = segments.join('/') const segmentPath = segments.join('/')
// Existing tree are the children of the current segment // Existing tree are the children of the current segment
...@@ -78,10 +80,9 @@ async function createTreeCodeFromPath({ ...@@ -78,10 +80,9 @@ async function createTreeCodeFromPath({
} }
const parallelSegmentPath = segmentPath + '/' + parallelSegment const parallelSegmentPath = segmentPath + '/' + parallelSegment
const subtree = await createSubtreePropsFromSegmentPath([ const { treeCode: subtreeCode } = await createSubtreePropsFromSegmentPath(
...segments, [...segments, parallelSegment]
parallelSegment, )
])
// `page` is not included here as it's added above. // `page` is not included here as it's added above.
const filePaths = await Promise.all( const filePaths = await Promise.all(
...@@ -93,10 +94,11 @@ async function createTreeCodeFromPath({ ...@@ -93,10 +94,11 @@ async function createTreeCodeFromPath({
}) })
) )
if (!rootLayout) { const layoutPath = filePaths.find(
rootLayout = filePaths.find(
([type, path]) => type === 'layout' && !!path ([type, path]) => type === 'layout' && !!path
)?.[1] )?.[1]
if (!rootLayout) {
rootLayout = layoutPath
} }
if (!globalError) { if (!globalError) {
...@@ -107,7 +109,7 @@ async function createTreeCodeFromPath({ ...@@ -107,7 +109,7 @@ async function createTreeCodeFromPath({
props[parallelKey] = `[ props[parallelKey] = `[
'${parallelSegment}', '${parallelSegment}',
${subtree}, ${subtreeCode},
{ {
${filePaths ${filePaths
.filter(([, filePath]) => filePath !== undefined) .filter(([, filePath]) => filePath !== undefined)
...@@ -115,6 +117,7 @@ async function createTreeCodeFromPath({ ...@@ -115,6 +117,7 @@ async function createTreeCodeFromPath({
if (filePath === undefined) { if (filePath === undefined) {
return '' return ''
} }
return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify( return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
filePath filePath
)}), ${JSON.stringify(filePath)}],` )}), ${JSON.stringify(filePath)}],`
...@@ -124,15 +127,22 @@ async function createTreeCodeFromPath({ ...@@ -124,15 +127,22 @@ async function createTreeCodeFromPath({
]` ]`
} }
return `{ return {
treeCode: `{
${Object.entries(props) ${Object.entries(props)
.map(([key, value]) => `${key}: ${value}`) .map(([key, value]) => `${key}: ${value}`)
.join(',\n')} .join(',\n')}
}` }`,
}
} }
const tree = await createSubtreePropsFromSegmentPath([]) const { treeCode } = await createSubtreePropsFromSegmentPath([])
return [`const tree = ${tree}.children;`, pages, rootLayout, globalError] return {
treeCode: `const tree = ${treeCode}.children;`,
pages,
rootLayout,
globalError,
}
} }
function createAbsolutePath(appDir: string, pathToTurnAbsolute: string) { function createAbsolutePath(appDir: string, pathToTurnAbsolute: string) {
...@@ -220,7 +230,7 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -220,7 +230,7 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
} }
} }
const [treeCode, pages, rootLayout, globalError] = const { treeCode, pages, rootLayout, globalError } =
await createTreeCodeFromPath({ await createTreeCodeFromPath({
pagePath, pagePath,
resolve: resolver, resolve: resolver,
......
...@@ -236,7 +236,7 @@ export class FlightClientEntryPlugin { ...@@ -236,7 +236,7 @@ export class FlightClientEntryPlugin {
// After optimizing all the modules, we collect the CSS that are still used // After optimizing all the modules, we collect the CSS that are still used
// by the certain chunk. // by the certain chunk.
compilation.hooks.afterOptimizeModules.tap(PLUGIN_NAME, () => { compilation.hooks.afterOptimizeModules.tap(PLUGIN_NAME, () => {
const cssImportsForChunk: Record<string, string[]> = {} const cssImportsForChunk: Record<string, Set<string>> = {}
if (this.isEdgeServer) { if (this.isEdgeServer) {
edgeServerCSSManifest = {} edgeServerCSSManifest = {}
} else { } else {
...@@ -252,7 +252,7 @@ export class FlightClientEntryPlugin { ...@@ -252,7 +252,7 @@ export class FlightClientEntryPlugin {
const modId = resource const modId = resource
if (modId) { if (modId) {
if (regexCSS.test(modId)) { if (regexCSS.test(modId)) {
cssImportsForChunk[entryName].push(modId) cssImportsForChunk[entryName].add(modId)
} }
} }
} }
...@@ -266,7 +266,7 @@ export class FlightClientEntryPlugin { ...@@ -266,7 +266,7 @@ export class FlightClientEntryPlugin {
const entryName = path.join(this.appDir, '..', chunk.name) const entryName = path.join(this.appDir, '..', chunk.name)
if (!cssImportsForChunk[entryName]) { if (!cssImportsForChunk[entryName]) {
cssImportsForChunk[entryName] = [] cssImportsForChunk[entryName] = new Set()
} }
const chunkModules = compilation.chunkGraph.getChunkModulesIterable( const chunkModules = compilation.chunkGraph.getChunkModulesIterable(
...@@ -285,7 +285,7 @@ export class FlightClientEntryPlugin { ...@@ -285,7 +285,7 @@ export class FlightClientEntryPlugin {
const entryCSSInfo: Record<string, string[]> = const entryCSSInfo: Record<string, string[]> =
cssManifest.__entry_css_mods__ || {} cssManifest.__entry_css_mods__ || {}
entryCSSInfo[entryName] = cssImportsForChunk[entryName] entryCSSInfo[entryName] = [...cssImportsForChunk[entryName]]
Object.assign(cssManifest, { Object.assign(cssManifest, {
__entry_css_mods__: entryCSSInfo, __entry_css_mods__: entryCSSInfo,
...@@ -318,12 +318,18 @@ export class FlightClientEntryPlugin { ...@@ -318,12 +318,18 @@ export class FlightClientEntryPlugin {
} }
}) })
const tracked = new Set<string>()
for (const connection of compilation.moduleGraph.getOutgoingConnections( for (const connection of compilation.moduleGraph.getOutgoingConnections(
entryModule entryModule
)) { )) {
const entryDependency = connection.dependency const entryDependency = connection.dependency
const entryRequest = connection.dependency.request 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] = const [, cssImports] =
this.collectClientComponentsAndCSSForDependency({ this.collectClientComponentsAndCSSForDependency({
entryRequest, entryRequest,
...@@ -403,7 +409,7 @@ export class FlightClientEntryPlugin { ...@@ -403,7 +409,7 @@ export class FlightClientEntryPlugin {
*/ */
const visitedBySegment: { [segment: string]: Set<string> } = {} const visitedBySegment: { [segment: string]: Set<string> } = {}
const clientComponentImports: ClientComponentImports = [] const clientComponentImports: ClientComponentImports = []
const serverCSSImports: CssImports = {} const CSSImports: CssImports = {}
const filterClientComponents = ( const filterClientComponents = (
dependencyToFilter: any, dependencyToFilter: any,
...@@ -451,8 +457,8 @@ export class FlightClientEntryPlugin { ...@@ -451,8 +457,8 @@ export class FlightClientEntryPlugin {
} }
} }
serverCSSImports[entryRequest] = serverCSSImports[entryRequest] || [] CSSImports[entryRequest] = CSSImports[entryRequest] || []
serverCSSImports[entryRequest].push(modRequest) CSSImports[entryRequest].push(modRequest)
} }
// Check if request is for css file. // Check if request is for css file.
...@@ -483,7 +489,7 @@ export class FlightClientEntryPlugin { ...@@ -483,7 +489,7 @@ export class FlightClientEntryPlugin {
// Traverse the module graph to find all client components. // Traverse the module graph to find all client components.
filterClientComponents(dependency, false) filterClientComponents(dependency, false)
return [clientComponentImports, serverCSSImports] return [clientComponentImports, CSSImports]
} }
injectClientEntryAndSSRModules({ injectClientEntryAndSSRModules({
......
...@@ -704,7 +704,9 @@ function getCssInlinedLinkTags( ...@@ -704,7 +704,9 @@ function getCssInlinedLinkTags(
serverComponentManifest: FlightManifest, serverComponentManifest: FlightManifest,
serverCSSManifest: FlightCSSManifest, serverCSSManifest: FlightCSSManifest,
filePath: string, filePath: string,
serverCSSForEntries: string[] serverCSSForEntries: string[],
injectedCSS: Set<string>,
collectNewCSSImports?: boolean
): string[] { ): string[] {
const layoutOrPageCssModules = serverCSSManifest[filePath] const layoutOrPageCssModules = serverCSSManifest[filePath]
...@@ -721,12 +723,26 @@ function getCssInlinedLinkTags( ...@@ -721,12 +723,26 @@ function getCssInlinedLinkTags(
for (const mod of layoutOrPageCssModules) { for (const mod of layoutOrPageCssModules) {
// We only include the CSS if it's a global CSS, or it is used by this // We only include the CSS if it's a global CSS, or it is used by this
// entrypoint. // entrypoint.
if (serverCSSForEntries.includes(mod) || !/\.module\.css/.test(mod)) { if (
serverCSSForEntries.includes(mod) ||
!/\.module\.(css|sass|scss)$/.test(mod)
) {
// If the CSS is already injected by a parent layer, we don't need
// to inject it again.
if (!injectedCSS.has(mod)) {
const modData = serverComponentManifest[mod] const modData = serverComponentManifest[mod]
if (modData) { if (modData) {
for (const chunk of modData.default.chunks) { for (const chunk of modData.default.chunks) {
// If the current entry in the final tree-shaked bundle has that CSS
// chunk, it means that it's actually used. We should include it.
if (cssFilesForEntry.has(chunk)) { if (cssFilesForEntry.has(chunk)) {
chunks.add(chunk) 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)
}
}
} }
} }
} }
...@@ -1098,16 +1114,19 @@ export async function renderToHTMLOrFlight( ...@@ -1098,16 +1114,19 @@ export async function renderToHTMLOrFlight(
filePath, filePath,
getComponent, getComponent,
shouldPreload, shouldPreload,
injectedCSS,
}: { }: {
filePath: string filePath: string
getComponent: () => any getComponent: () => any
shouldPreload?: boolean shouldPreload?: boolean
injectedCSS: Set<string>
}): Promise<any> => { }): Promise<any> => {
const cssHrefs = getCssInlinedLinkTags( const cssHrefs = getCssInlinedLinkTags(
serverComponentManifest, serverComponentManifest,
serverCSSManifest, serverCSSManifest,
filePath, filePath,
serverCSSForEntries serverCSSForEntries,
injectedCSS
) )
const styles = cssHrefs const styles = cssHrefs
...@@ -1144,20 +1163,26 @@ export async function renderToHTMLOrFlight( ...@@ -1144,20 +1163,26 @@ export async function renderToHTMLOrFlight(
parentParams, parentParams,
firstItem, firstItem,
rootLayoutIncluded, rootLayoutIncluded,
injectedCSS,
}: { }: {
createSegmentPath: CreateSegmentPath createSegmentPath: CreateSegmentPath
loaderTree: LoaderTree loaderTree: LoaderTree
parentParams: { [key: string]: any } parentParams: { [key: string]: any }
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
firstItem?: boolean firstItem?: boolean
injectedCSS: Set<string>
}): Promise<{ Component: React.ComponentType }> => { }): Promise<{ Component: React.ComponentType }> => {
const layoutOrPagePath = layout?.[1] || page?.[1] const layoutOrPagePath = layout?.[1] || page?.[1]
const injectedCSSWithCurrentLayout = new Set(injectedCSS)
const stylesheets: string[] = layoutOrPagePath const stylesheets: string[] = layoutOrPagePath
? getCssInlinedLinkTags( ? getCssInlinedLinkTags(
serverComponentManifest, serverComponentManifest,
serverCSSManifest!, serverCSSManifest!,
layoutOrPagePath, layoutOrPagePath,
serverCSSForEntries serverCSSForEntries,
injectedCSSWithCurrentLayout,
true
) )
: [] : []
...@@ -1176,6 +1201,7 @@ export async function renderToHTMLOrFlight( ...@@ -1176,6 +1201,7 @@ export async function renderToHTMLOrFlight(
filePath: template[1], filePath: template[1],
getComponent: template[0], getComponent: template[0],
shouldPreload: true, shouldPreload: true,
injectedCSS: injectedCSSWithCurrentLayout,
}) })
: [React.Fragment] : [React.Fragment]
...@@ -1183,6 +1209,7 @@ export async function renderToHTMLOrFlight( ...@@ -1183,6 +1209,7 @@ export async function renderToHTMLOrFlight(
? await createComponentAndStyles({ ? await createComponentAndStyles({
filePath: error[1], filePath: error[1],
getComponent: error[0], getComponent: error[0],
injectedCSS: injectedCSSWithCurrentLayout,
}) })
: [] : []
...@@ -1190,6 +1217,7 @@ export async function renderToHTMLOrFlight( ...@@ -1190,6 +1217,7 @@ export async function renderToHTMLOrFlight(
? await createComponentAndStyles({ ? await createComponentAndStyles({
filePath: loading[1], filePath: loading[1],
getComponent: loading[0], getComponent: loading[0],
injectedCSS: injectedCSSWithCurrentLayout,
}) })
: [] : []
...@@ -1215,6 +1243,7 @@ export async function renderToHTMLOrFlight( ...@@ -1215,6 +1243,7 @@ export async function renderToHTMLOrFlight(
? await createComponentAndStyles({ ? await createComponentAndStyles({
filePath: notFound[1], filePath: notFound[1],
getComponent: notFound[0], getComponent: notFound[0],
injectedCSS: injectedCSSWithCurrentLayout,
}) })
: rootLayoutAtThisLevel : rootLayoutAtThisLevel
? [DefaultNotFound] ? [DefaultNotFound]
...@@ -1354,6 +1383,7 @@ export async function renderToHTMLOrFlight( ...@@ -1354,6 +1383,7 @@ export async function renderToHTMLOrFlight(
loaderTree: parallelRoutes[parallelRouteKey], loaderTree: parallelRoutes[parallelRouteKey],
parentParams: currentParams, parentParams: currentParams,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
injectedCSS: injectedCSSWithCurrentLayout,
}) })
const childProp: ChildProp = { const childProp: ChildProp = {
...@@ -1500,6 +1530,7 @@ export async function renderToHTMLOrFlight( ...@@ -1500,6 +1530,7 @@ export async function renderToHTMLOrFlight(
flightRouterState, flightRouterState,
parentRendered, parentRendered,
rscPayloadHead, rscPayloadHead,
injectedCSS,
rootLayoutIncluded, rootLayoutIncluded,
}: { }: {
createSegmentPath: CreateSegmentPath createSegmentPath: CreateSegmentPath
...@@ -1509,6 +1540,7 @@ export async function renderToHTMLOrFlight( ...@@ -1509,6 +1540,7 @@ export async function renderToHTMLOrFlight(
flightRouterState?: FlightRouterState flightRouterState?: FlightRouterState
parentRendered?: boolean parentRendered?: boolean
rscPayloadHead: React.ReactNode rscPayloadHead: React.ReactNode
injectedCSS: Set<string>
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
}): Promise<FlightDataPath> => { }): Promise<FlightDataPath> => {
const [segment, parallelRoutes, { layout }] = loaderTreeToFilter const [segment, parallelRoutes, { layout }] = loaderTreeToFilter
...@@ -1572,6 +1604,7 @@ export async function renderToHTMLOrFlight( ...@@ -1572,6 +1604,7 @@ export async function renderToHTMLOrFlight(
loaderTree: loaderTreeToFilter, loaderTree: loaderTreeToFilter,
parentParams: currentParams, parentParams: currentParams,
firstItem: isFirst, firstItem: isFirst,
injectedCSS,
// This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too. // This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too.
rootLayoutIncluded: rootLayoutIncluded, rootLayoutIncluded: rootLayoutIncluded,
} }
...@@ -1584,6 +1617,22 @@ export async function renderToHTMLOrFlight( ...@@ -1584,6 +1617,22 @@ export async function renderToHTMLOrFlight(
] ]
} }
// If we are not rendering on this level we need to check if the current
// segment has a layout. If so, we need to track all the used CSS to make
// the result consistent.
const layoutPath = layout?.[1]
const injectedCSSWithCurrentLayout = new Set(injectedCSS)
if (layoutPath) {
getCssInlinedLinkTags(
serverComponentManifest,
serverCSSManifest!,
layoutPath,
serverCSSForEntries,
injectedCSSWithCurrentLayout,
true
)
}
// Walk through all parallel routes. // Walk through all parallel routes.
for (const parallelRouteKey of parallelRoutesKeys) { for (const parallelRouteKey of parallelRoutesKeys) {
const parallelRoute = parallelRoutes[parallelRouteKey] const parallelRoute = parallelRoutes[parallelRouteKey]
...@@ -1603,6 +1652,7 @@ export async function renderToHTMLOrFlight( ...@@ -1603,6 +1652,7 @@ export async function renderToHTMLOrFlight(
parentRendered: parentRendered || renderComponentsOnThisLevel, parentRendered: parentRendered || renderComponentsOnThisLevel,
isFirst: false, isFirst: false,
rscPayloadHead, rscPayloadHead,
injectedCSS: injectedCSSWithCurrentLayout,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
}) })
...@@ -1626,6 +1676,7 @@ export async function renderToHTMLOrFlight( ...@@ -1626,6 +1676,7 @@ export async function renderToHTMLOrFlight(
flightRouterState: providedFlightRouterState, flightRouterState: providedFlightRouterState,
isFirst: true, isFirst: true,
rscPayloadHead, rscPayloadHead,
injectedCSS: new Set(),
rootLayoutIncluded: false, rootLayoutIncluded: false,
}) })
).slice(1), ).slice(1),
...@@ -1705,6 +1756,7 @@ export async function renderToHTMLOrFlight( ...@@ -1705,6 +1756,7 @@ export async function renderToHTMLOrFlight(
loaderTree: loaderTree, loaderTree: loaderTree,
parentParams: {}, parentParams: {},
firstItem: true, firstItem: true,
injectedCSS: new Set(),
rootLayoutIncluded: false, rootLayoutIncluded: false,
}) })
const initialTree = createFlightRouterStateFromLoaderTree(loaderTree) const initialTree = createFlightRouterStateFromLoaderTree(loaderTree)
......
'use client'
import styles from '../style.module.css'
export default function Page() {
return <div className={styles.foo}>Hello</div>
}
import styles from './style.module.css'
export default function Layout({ children }) {
return <div className={styles.foo}>{children}</div>
}
import styles from '../style.module.css'
export default function Page() {
return <div className={styles.foo}>Hello</div>
}
.foo::before {
content: '_randomized_string_for_testing_';
}
...@@ -1466,6 +1466,27 @@ createNextDescribe( ...@@ -1466,6 +1466,27 @@ createNextDescribe(
if (isDev) { if (isDev) {
describe('multiple entries', () => { describe('multiple entries', () => {
it('should only inject the same style once if used by different layers', async () => {
const browser = await next.browser('/css/css-duplicate-2/client')
expect(
await browser.eval(
`[...document.styleSheets].filter(({ cssRules }) =>
[...cssRules].some(({ cssText }) => (cssText||'').includes('_randomized_string_for_testing_'))
).length`
)
).toBe(1)
})
it('should only include the same style once in the flight data', async () => {
const initialHtml = await next.render('/css/css-duplicate-2/server')
// Even if it's deduped by Float, it should still only be included once in the payload.
// There are two matches, one for the rendered <link> and one for the flight data.
expect(
initialHtml.match(/duplicate-2_style_module_css\.css/g).length
).toBe(2)
})
it('should only load chunks for the css module that is used by the specific entrypoint', async () => { it('should only load chunks for the css module that is used by the specific entrypoint', async () => {
// Visit /b first // Visit /b first
await next.render('/css/css-duplicate/b') await next.render('/css/css-duplicate/b')
......
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