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

Refactor client CSS imports (#39758)

Removed the hack of client-side CSS injection via `chunk`. Instead collect them with the manifest plugin and SSR them as link tags.

Next step is to adjust HMR to not relying on mini-css-extract plugin and webpack.
parent 3d0d0900
......@@ -71,11 +71,6 @@ export class FlightClientEntryPlugin {
// For each SC server compilation entry, we need to create its corresponding
// client component entry.
for (const [name, entry] of compilation.entries.entries()) {
// If the request is not for `app` directory entry skip it.
// if (!entry.request || !entry.request.startsWith('next-app-loader')) {
// continue
// }
// Check if the page entry is a server component or not.
const entryDependency = entry.dependencies?.[0]
// Ensure only next-app-loader entries are handled.
......@@ -193,7 +188,10 @@ export class FlightClientEntryPlugin {
const clientComponentImports: ClientComponentImports = []
const serverCSSImports: CssImports = {}
const filterClientComponents = (dependencyToFilter: any): void => {
const filterClientComponents = (
dependencyToFilter: any,
inClientComponentBoundary: boolean
): void => {
const mod: webpack.NormalModule =
compilation.moduleGraph.getResolvedModule(dependencyToFilter)
if (!mod) return
......@@ -236,7 +234,7 @@ export class FlightClientEntryPlugin {
}
// Check if request is for css file.
if (isClientComponent || isCSS) {
if ((!inClientComponentBoundary && isClientComponent) || isCSS) {
clientComponentImports.push(modRequest)
return
}
......@@ -244,12 +242,15 @@ export class FlightClientEntryPlugin {
compilation.moduleGraph
.getOutgoingConnections(mod)
.forEach((connection: any) => {
filterClientComponents(connection.dependency)
filterClientComponents(
connection.dependency,
inClientComponentBoundary || isClientComponent
)
})
}
// Traverse the module graph to find all client components.
filterClientComponents(dependency)
filterClientComponents(dependency, false)
return [clientComponentImports, serverCSSImports]
}
......
......@@ -114,6 +114,9 @@ export class FlightManifestPlugin {
const dev = this.dev
compilation.chunkGroups.forEach((chunkGroup) => {
const cssResourcesInChunkGroup: string[] = []
let entryFilepath: string = ''
function recordModule(
chunk: webpack.Chunk,
id: ModuleId,
......@@ -176,6 +179,11 @@ export class FlightManifestPlugin {
}
manifest.__ssr_module_mapping__ = moduleIdMapping
}
if (chunkGroup.name) {
cssResourcesInChunkGroup.push(resource)
}
return
}
......@@ -186,6 +194,10 @@ export class FlightManifestPlugin {
return
}
if (/\/(page|layout)\.client\.(ts|js)x?$/.test(resource)) {
entryFilepath = resource
}
const exportsInfo = compilation.moduleGraph.getExportsInfo(mod)
const cjsExports = [
...new Set([
......@@ -218,37 +230,6 @@ export class FlightManifestPlugin {
)
.filter((name) => name !== null)
// Get all CSS files imported from the module's dependencies.
const visitedModule = new Set()
const cssChunks: Set<string> = new Set()
function collectClientImportedCss(module: any) {
if (!module) return
const modRequest = module.userRequest
if (visitedModule.has(modRequest)) return
visitedModule.add(modRequest)
if (/\.css$/.test(modRequest)) {
// collect relative imported css chunks
compilation.chunkGraph.getModuleChunks(module).forEach((c) => {
;[...c.files]
.filter((file) => file.endsWith('.css'))
.forEach((file) => cssChunks.add(file))
})
}
const connections = Array.from(
compilation.moduleGraph.getOutgoingConnections(module)
)
connections.forEach((connection) => {
collectClientImportedCss(
compilation.moduleGraph.getResolvedModule(connection.dependency!)
)
})
}
collectClientImportedCss(mod)
moduleExportedKeys.forEach((name) => {
let requiredChunks: ManifestChunks = []
if (!moduleExports[name]) {
......@@ -273,7 +254,7 @@ export class FlightManifestPlugin {
moduleExports[name] = {
id,
name,
chunks: requiredChunks.concat([...cssChunks]),
chunks: requiredChunks,
}
}
......@@ -310,6 +291,12 @@ export class FlightManifestPlugin {
}
}
})
const clientCSSManifest: any = manifest.__client_css_manifest__ || {}
if (entryFilepath) {
clientCSSManifest[entryFilepath] = cssResourcesInChunkGroup
}
manifest.__client_css_manifest__ = clientCSSManifest
})
const file = 'server/' + FLIGHT_MANIFEST
......
......@@ -32,18 +32,6 @@ self.__next_require__ = __webpack_require__
// eslint-disable-next-line no-undef
;(self as any).__next_chunk_load__ = (chunk: string) => {
if (!chunk) return Promise.resolve()
if (chunk.endsWith('.css')) {
// @ts-expect-error __webpack_public_path__ is inlined by webpack
const chunkPath = `${__webpack_public_path__ || ''}${chunk}`
const existingTag = document.querySelector(`link[href="${chunkPath}"]`)
if (!existingTag) {
const link = document.createElement('link')
link.rel = 'stylesheet'
link.href = chunkPath
document.head.appendChild(link)
}
return Promise.resolve()
}
const [chunkId, chunkFileName] = chunk.split(':')
chunkFilenameMap[chunkId] = `static/chunks/${chunkFileName}.js`
......
......@@ -383,7 +383,9 @@ function getCssInlinedLinkTags(
serverCSSManifest: FlightCSSManifest,
filePath: string
): string[] {
const layoutOrPageCss = serverCSSManifest[filePath]
const layoutOrPageCss =
serverCSSManifest[filePath] ||
serverComponentManifest.__client_css_manifest__?.[filePath]
if (!layoutOrPageCss) {
return []
......
h1 {
color: red !important;
}
h1::after {
content: ' (from css-client!!)';
}
import './client-foo.css'
export default function Foo() {
return <b className="foo">foo</b>
}
import './client-layout.css'
import Foo from './foo'
export default function ServerLayout({ children }) {
return (
<>
{children}
<Foo />
</>
)
}
import './client-page.css'
export default function Page() {
return <h1>Page!!!</h1>
}
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