Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix CSS imports being tracked multiple times #44938

Merged
merged 7 commits into from
Jan 17, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 27 additions & 17 deletions packages/next/src/build/webpack/loaders/next-app-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ async function createTreeCodeFromPath({

async function createSubtreePropsFromSegmentPath(
segments: string[]
): Promise<string> {
): Promise<{
treeCode: string
}> {
const segmentPath = segments.join('/')

// Existing tree are the children of the current segment
Expand Down Expand Up @@ -78,10 +80,9 @@ async function createTreeCodeFromPath({
}

const parallelSegmentPath = segmentPath + '/' + parallelSegment
const subtree = await createSubtreePropsFromSegmentPath([
...segments,
parallelSegment,
])
const { treeCode: subtreeCode } = await createSubtreePropsFromSegmentPath(
[...segments, parallelSegment]
)

// `page` is not included here as it's added above.
const filePaths = await Promise.all(
Expand All @@ -93,10 +94,11 @@ async function createTreeCodeFromPath({
})
)

const layoutPath = filePaths.find(
([type, path]) => type === 'layout' && !!path
)?.[1]
if (!rootLayout) {
rootLayout = filePaths.find(
([type, path]) => type === 'layout' && !!path
)?.[1]
rootLayout = layoutPath
}

if (!globalError) {
Expand All @@ -107,14 +109,15 @@ async function createTreeCodeFromPath({

props[parallelKey] = `[
'${parallelSegment}',
${subtree},
${subtreeCode},
{
${filePaths
.filter(([, filePath]) => filePath !== undefined)
.map(([file, filePath]) => {
if (filePath === undefined) {
return ''
}

return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
filePath
)}), ${JSON.stringify(filePath)}],`
Expand All @@ -124,15 +127,22 @@ async function createTreeCodeFromPath({
]`
}

return `{
${Object.entries(props)
.map(([key, value]) => `${key}: ${value}`)
.join(',\n')}
}`
return {
treeCode: `{
${Object.entries(props)
.map(([key, value]) => `${key}: ${value}`)
.join(',\n')}
}`,
}
}

const tree = await createSubtreePropsFromSegmentPath([])
return [`const tree = ${tree}.children;`, pages, rootLayout, globalError]
const { treeCode } = await createSubtreePropsFromSegmentPath([])
return {
treeCode: `const tree = ${treeCode}.children;`,
pages,
rootLayout,
globalError,
}
}

function createAbsolutePath(appDir: string, pathToTurnAbsolute: string) {
Expand Down Expand Up @@ -220,7 +230,7 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
}
}

const [treeCode, pages, rootLayout, globalError] =
const { treeCode, pages, rootLayout, globalError } =
await createTreeCodeFromPath({
pagePath,
resolve: resolver,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ export class FlightClientEntryPlugin {
// 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, string[]> = {}
const cssImportsForChunk: Record<string, Set<string>> = {}
if (this.isEdgeServer) {
edgeServerCSSManifest = {}
} else {
Expand All @@ -252,7 +252,7 @@ export class FlightClientEntryPlugin {
const modId = resource
if (modId) {
if (regexCSS.test(modId)) {
cssImportsForChunk[entryName].push(modId)
cssImportsForChunk[entryName].add(modId)
}
}
}
Expand All @@ -266,7 +266,7 @@ export class FlightClientEntryPlugin {
const entryName = path.join(this.appDir, '..', chunk.name)

if (!cssImportsForChunk[entryName]) {
cssImportsForChunk[entryName] = []
cssImportsForChunk[entryName] = new Set()
}

const chunkModules = compilation.chunkGraph.getChunkModulesIterable(
Expand All @@ -285,7 +285,7 @@ export class FlightClientEntryPlugin {

const entryCSSInfo: Record<string, string[]> =
cssManifest.__entry_css_mods__ || {}
entryCSSInfo[entryName] = cssImportsForChunk[entryName]
entryCSSInfo[entryName] = [...cssImportsForChunk[entryName]]

Object.assign(cssManifest, {
__entry_css_mods__: entryCSSInfo,
Expand Down Expand Up @@ -318,12 +318,18 @@ export class FlightClientEntryPlugin {
}
})

const tracked = new Set<string>()
for (const connection of compilation.moduleGraph.getOutgoingConnections(
entryModule
)) {
const entryDependency = connection.dependency
const entryRequest = connection.dependency.request

// It is possible that the same entry is added multiple times in the
// connection graph. We can just skip these to speed up the process.
if (tracked.has(entryRequest)) continue
tracked.add(entryRequest)

const [, cssImports] =
this.collectClientComponentsAndCSSForDependency({
entryRequest,
Expand Down Expand Up @@ -403,7 +409,7 @@ export class FlightClientEntryPlugin {
*/
const visitedBySegment: { [segment: string]: Set<string> } = {}
const clientComponentImports: ClientComponentImports = []
const serverCSSImports: CssImports = {}
const CSSImports: CssImports = {}

const filterClientComponents = (
dependencyToFilter: any,
Expand Down Expand Up @@ -451,8 +457,8 @@ export class FlightClientEntryPlugin {
}
}

serverCSSImports[entryRequest] = serverCSSImports[entryRequest] || []
serverCSSImports[entryRequest].push(modRequest)
CSSImports[entryRequest] = CSSImports[entryRequest] || []
CSSImports[entryRequest].push(modRequest)
}

// Check if request is for css file.
Expand Down Expand Up @@ -483,7 +489,7 @@ export class FlightClientEntryPlugin {
// Traverse the module graph to find all client components.
filterClientComponents(dependency, false)

return [clientComponentImports, serverCSSImports]
return [clientComponentImports, CSSImports]
}

injectClientEntryAndSSRModules({
Expand Down
70 changes: 61 additions & 9 deletions packages/next/src/server/app-render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,9 @@ function getCssInlinedLinkTags(
serverComponentManifest: FlightManifest,
serverCSSManifest: FlightCSSManifest,
filePath: string,
serverCSSForEntries: string[]
serverCSSForEntries: string[],
injectedCSS: Set<string>,
collectNewCSSImports?: boolean
): string[] {
const layoutOrPageCssModules = serverCSSManifest[filePath]

Expand All @@ -721,12 +723,26 @@ function getCssInlinedLinkTags(
for (const mod of layoutOrPageCssModules) {
// We only include the CSS if it's a global CSS, or it is used by this
// entrypoint.
if (serverCSSForEntries.includes(mod) || !/\.module\.css/.test(mod)) {
const modData = serverComponentManifest[mod]
if (modData) {
for (const chunk of modData.default.chunks) {
if (cssFilesForEntry.has(chunk)) {
chunks.add(chunk)
if (
serverCSSForEntries.includes(mod) ||
!/\.module\.(css|sass)$/.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]
if (modData) {
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)) {
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)
}
}
}
}
}
Expand Down Expand Up @@ -1098,16 +1114,19 @@ export async function renderToHTMLOrFlight(
filePath,
getComponent,
shouldPreload,
injectedCSS,
}: {
filePath: string
getComponent: () => any
shouldPreload?: boolean
injectedCSS: Set<string>
}): Promise<any> => {
const cssHrefs = getCssInlinedLinkTags(
serverComponentManifest,
serverCSSManifest,
filePath,
serverCSSForEntries
serverCSSForEntries,
injectedCSS
)

const styles = cssHrefs
Expand Down Expand Up @@ -1144,20 +1163,26 @@ export async function renderToHTMLOrFlight(
parentParams,
firstItem,
rootLayoutIncluded,
injectedCSS,
}: {
createSegmentPath: CreateSegmentPath
loaderTree: LoaderTree
parentParams: { [key: string]: any }
rootLayoutIncluded: boolean
firstItem?: boolean
injectedCSS: Set<string>
}): Promise<{ Component: React.ComponentType }> => {
const layoutOrPagePath = layout?.[1] || page?.[1]

const injectedCSSWithCurrentLayout = new Set(injectedCSS)
const stylesheets: string[] = layoutOrPagePath
? getCssInlinedLinkTags(
serverComponentManifest,
serverCSSManifest!,
layoutOrPagePath,
serverCSSForEntries
serverCSSForEntries,
injectedCSSWithCurrentLayout,
true
)
: []

Expand All @@ -1176,20 +1201,23 @@ export async function renderToHTMLOrFlight(
filePath: template[1],
getComponent: template[0],
shouldPreload: true,
injectedCSS: injectedCSSWithCurrentLayout,
})
: [React.Fragment]

const [ErrorComponent, errorStyles] = error
? await createComponentAndStyles({
filePath: error[1],
getComponent: error[0],
injectedCSS: injectedCSSWithCurrentLayout,
})
: []

const [Loading, loadingStyles] = loading
? await createComponentAndStyles({
filePath: loading[1],
getComponent: loading[0],
injectedCSS: injectedCSSWithCurrentLayout,
})
: []

Expand All @@ -1215,6 +1243,7 @@ export async function renderToHTMLOrFlight(
? await createComponentAndStyles({
filePath: notFound[1],
getComponent: notFound[0],
injectedCSS: injectedCSSWithCurrentLayout,
})
: rootLayoutAtThisLevel
? [DefaultNotFound]
Expand Down Expand Up @@ -1354,6 +1383,7 @@ export async function renderToHTMLOrFlight(
loaderTree: parallelRoutes[parallelRouteKey],
parentParams: currentParams,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
injectedCSS: injectedCSSWithCurrentLayout,
})

const childProp: ChildProp = {
Expand Down Expand Up @@ -1500,6 +1530,7 @@ export async function renderToHTMLOrFlight(
flightRouterState,
parentRendered,
rscPayloadHead,
injectedCSS,
rootLayoutIncluded,
}: {
createSegmentPath: CreateSegmentPath
Expand All @@ -1509,6 +1540,7 @@ export async function renderToHTMLOrFlight(
flightRouterState?: FlightRouterState
parentRendered?: boolean
rscPayloadHead: React.ReactNode
injectedCSS: Set<string>
rootLayoutIncluded: boolean
}): Promise<FlightDataPath> => {
const [segment, parallelRoutes, { layout }] = loaderTreeToFilter
Expand Down Expand Up @@ -1572,6 +1604,7 @@ export async function renderToHTMLOrFlight(
loaderTree: loaderTreeToFilter,
parentParams: currentParams,
firstItem: isFirst,
injectedCSS,
// This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too.
rootLayoutIncluded: rootLayoutIncluded,
}
Expand All @@ -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(
huozhi marked this conversation as resolved.
Show resolved Hide resolved
serverComponentManifest,
serverCSSManifest!,
layoutPath,
serverCSSForEntries,
injectedCSSWithCurrentLayout,
true
)
}

// Walk through all parallel routes.
for (const parallelRouteKey of parallelRoutesKeys) {
const parallelRoute = parallelRoutes[parallelRouteKey]
Expand All @@ -1603,6 +1652,7 @@ export async function renderToHTMLOrFlight(
parentRendered: parentRendered || renderComponentsOnThisLevel,
isFirst: false,
rscPayloadHead,
injectedCSS: injectedCSSWithCurrentLayout,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
})

Expand All @@ -1626,6 +1676,7 @@ export async function renderToHTMLOrFlight(
flightRouterState: providedFlightRouterState,
isFirst: true,
rscPayloadHead,
injectedCSS: new Set(),
rootLayoutIncluded: false,
})
).slice(1),
Expand Down Expand Up @@ -1705,6 +1756,7 @@ export async function renderToHTMLOrFlight(
loaderTree: loaderTree,
parentParams: {},
firstItem: true,
injectedCSS: new Set(),
rootLayoutIncluded: false,
})
const initialTree = createFlightRouterStateFromLoaderTree(loaderTree)
Expand Down
7 changes: 7 additions & 0 deletions test/e2e/app-dir/app/app/css/css-duplicate-2/client/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use client'

import styles from '../style.module.css'

export default function Page() {
return <div className={styles.foo}>Hello</div>
}
5 changes: 5 additions & 0 deletions test/e2e/app-dir/app/app/css/css-duplicate-2/layout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import styles from './style.module.css'

export default function Layout({ children }) {
return <div className={styles.foo}>{children}</div>
}
Loading