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