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

HMR for client CSS imports (#39916)

Follow-up to #39758, this PR makes sure that CSS imports (both global and CSS modules) from client components are not handled by mini-css-extract's HMR logic. Instead, we trigger a server component update and let the client to refetch the RSC payload.

However, we are still leveraging the mini-css-extract plugin to emit CSS assets. So in this PR we add a new pitch loader to calculate the original file hash, but replace the final content to eliminate HMR logic but only keep the hash (so hot reloader can keep tracking that).

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `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`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
parent a799d25c
......@@ -40,8 +40,10 @@ export function getClientStyleLoader({
const MiniCssExtractPlugin =
require('../../../../plugins/mini-css-extract-plugin').default
return {
// @ts-ignore: TODO: remove when webpack 5 is stable
loader: MiniCssExtractPlugin.loader,
options: { publicPath: `${assetPrefix}/_next/`, esModule: false },
options: {
publicPath: `${assetPrefix}/_next/`,
esModule: false,
},
}
}
......@@ -4,13 +4,26 @@
* inside a comment.
*/
const NextServerCSSLoader = function (this: any, source: string | Buffer) {
export function pitch(this: any) {
const content = this.fs.readFileSync(this.resource)
this.data.__checksum = (
typeof content === 'string' ? Buffer.from(content) : content
).toString('hex')
}
const NextServerCSSLoader = function (this: any, content: string) {
this.cacheable && this.cacheable()
return `export default "${(typeof source === 'string'
? Buffer.from(source)
: source
).toString('hex')}"`
const isCSSModule = this.resource.match(/\.module\.css$/)
if (isCSSModule) {
return (
content +
'\nmodule.exports.__checksum = ' +
JSON.stringify(this.data.__checksum)
)
}
return `export default ${JSON.stringify(this.data.__checksum)}`
}
export default NextServerCSSLoader
......@@ -113,7 +113,7 @@ export class FlightManifestPlugin {
const dev = this.dev
compilation.chunkGroups.forEach((chunkGroup) => {
const cssResourcesInChunkGroup: string[] = []
const cssResourcesInChunkGroup = new Set<string>()
let entryFilepath: string = ''
function recordModule(
......@@ -170,17 +170,10 @@ export class FlightManifestPlugin {
chunks,
},
}
moduleIdMapping[id] = moduleIdMapping[id] || {}
moduleIdMapping[id]['default'] = {
id: ssrNamedModuleId,
name: 'default',
chunks,
}
manifest.__ssr_module_mapping__ = moduleIdMapping
}
if (chunkGroup.name) {
cssResourcesInChunkGroup.push(resource)
cssResourcesInChunkGroup.add(resource)
}
return
......@@ -297,7 +290,7 @@ export class FlightManifestPlugin {
const clientCSSManifest: any = manifest.__client_css_manifest__ || {}
if (entryFilepath) {
clientCSSManifest[entryFilepath] = cssResourcesInChunkGroup
clientCSSManifest[entryFilepath] = Array.from(cssResourcesInChunkGroup)
}
manifest.__client_css_manifest__ = clientCSSManifest
})
......
......@@ -393,8 +393,11 @@ function getCssInlinedLinkTags(
const chunks = new Set<string>()
for (const css of layoutOrPageCss) {
for (const chunk of serverComponentManifest[css].default.chunks) {
chunks.add(chunk)
const mod = serverComponentManifest[css]
if (mod) {
for (const chunk of mod.default.chunks) {
chunks.add(chunk)
}
}
}
......
......@@ -726,9 +726,12 @@ export default class HotReloader {
const changedClientPages = new Set<string>()
const changedServerPages = new Set<string>()
const changedEdgeServerPages = new Set<string>()
const changedCSSImportPages = new Set<string>()
const prevClientPageHashes = new Map<string, string>()
const prevServerPageHashes = new Map<string, string>()
const prevEdgeServerPageHashes = new Map<string, string>()
const prevCSSImportModuleHashes = new Map<string, string>()
const trackPageChanges =
(pageHashMap: Map<string, string>, changedItems: Set<string>) =>
......@@ -746,6 +749,7 @@ export default class HotReloader {
const modsIterable: any =
stats.chunkGraph.getChunkModulesIterable(chunk)
let hasCSSModuleChanges = false
let chunksHash = new StringXor()
modsIterable.forEach((mod: any) => {
......@@ -771,6 +775,21 @@ export default class HotReloader {
chunk.runtime
)
chunksHash.add(hash)
// Both CSS import changes from server and client
// components are tracked.
if (
key.startsWith('app/') &&
mod.resource?.endsWith('.css')
) {
const prevHash = prevCSSImportModuleHashes.get(
mod.resource
)
if (prevHash && prevHash !== hash) {
hasCSSModuleChanges = true
}
prevCSSImportModuleHashes.set(mod.resource, hash)
}
}
})
const prevHash = pageHashMap.get(key)
......@@ -780,6 +799,10 @@ export default class HotReloader {
changedItems.add(key)
}
pageHashMap.set(key, curHash)
if (hasCSSModuleChanges) {
changedCSSImportPages.add(key)
}
}
})
}
......@@ -857,18 +880,20 @@ export default class HotReloader {
changedServerPages,
changedClientPages
)
const serverComponentChanges = serverOnlyChanges.filter((key) =>
key.startsWith('app/')
)
const serverComponentChanges = serverOnlyChanges
.filter((key) => key.startsWith('app/'))
.concat(Array.from(changedCSSImportPages))
const pageChanges = serverOnlyChanges.filter((key) =>
key.startsWith('pages/')
)
const middlewareChanges = Array.from(changedEdgeServerPages).filter(
(name) => isMiddlewareFilename(name)
)
changedClientPages.clear()
changedServerPages.clear()
changedEdgeServerPages.clear()
changedCSSImportPages.clear()
if (middlewareChanges.length > 0) {
this.send({
......
......@@ -2,5 +2,5 @@ h1 {
color: red !important;
}
h1::after {
content: ' (from css-client!!)';
content: ' (from css-client!!!!)';
}
......@@ -5,7 +5,7 @@ import styles from './style.module.css'
export default function ServerLayout({ children }) {
return (
<>
<div id="server-cssm" className={styles['server-css']}>
<div id="server-cssm" className={styles['server-css'] || 'undefined'}>
Server Layout: CSS Modules
</div>
<div className="server-css">Server Layout: Global CSS</div>
......
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