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
...@@ -201,6 +201,67 @@ export const css = curry(async function css( ...@@ -201,6 +201,67 @@ export const css = curry(async function css(
// CSS Modules support must be enabled on the server and client so the class // CSS Modules support must be enabled on the server and client so the class
// names are available for SSR or Prerendering. // names are available for SSR or Prerendering.
if (ctx.experimental.appDir && !ctx.isProduction) {
fns.push(
loader({
oneOf: [
markRemovable({
// CSS Modules should never have side effects. This setting will
// allow unused CSS to be removed from the production build.
// We ensure this by disallowing `:global()` CSS at the top-level
// via the `pure` mode in `css-loader`.
sideEffects: false,
// CSS Modules are activated via this specific extension.
test: regexCssModules,
// CSS Modules are only supported in the user's application. We're
// not yet allowing CSS imports _within_ `node_modules`.
issuer: {
and: [
{
or: [ctx.rootDirectory, regexClientEntry],
},
],
not: [/node_modules/],
},
use: [
require.resolve('../../../loaders/next-flight-css-dev-loader'),
...getCssModuleLoader(ctx, lazyPostCSSInitializer),
],
}),
],
})
)
fns.push(
loader({
oneOf: [
// Opt-in support for Sass (using .scss or .sass extensions).
markRemovable({
// Sass Modules should never have side effects. This setting will
// allow unused Sass to be removed from the production build.
// We ensure this by disallowing `:global()` Sass at the top-level
// via the `pure` mode in `css-loader`.
sideEffects: false,
// Sass Modules are activated via this specific extension.
test: regexSassModules,
// Sass Modules are only supported in the user's application. We're
// not yet allowing Sass imports _within_ `node_modules`.
issuer: {
and: [ctx.rootDirectory],
not: [/node_modules/],
},
use: [
require.resolve('../../../loaders/next-flight-css-dev-loader'),
...getCssModuleLoader(
ctx,
lazyPostCSSInitializer,
sassPreprocessors
),
],
}),
],
})
)
} else {
fns.push( fns.push(
loader({ loader({
oneOf: [ oneOf: [
...@@ -254,6 +315,7 @@ export const css = curry(async function css( ...@@ -254,6 +315,7 @@ export const css = curry(async function css(
], ],
}) })
) )
}
if (!ctx.experimental.appDir) { if (!ctx.experimental.appDir) {
// Throw an error for CSS Modules used outside their supported scope // Throw an error for CSS Modules used outside their supported scope
...@@ -280,6 +342,7 @@ export const css = curry(async function css( ...@@ -280,6 +342,7 @@ export const css = curry(async function css(
loader({ loader({
oneOf: [ oneOf: [
markRemovable({ markRemovable({
sideEffects: true,
test: [regexCssGlobal, regexSassGlobal], test: [regexCssGlobal, regexSassGlobal],
use: require.resolve( use: require.resolve(
'../../../loaders/next-flight-css-dev-loader' '../../../loaders/next-flight-css-dev-loader'
...@@ -300,6 +363,40 @@ export const css = curry(async function css( ...@@ -300,6 +363,40 @@ export const css = curry(async function css(
}) })
) )
} }
} else {
if (ctx.experimental.appDir) {
fns.push(
loader({
oneOf: [
markRemovable({
// A global CSS import always has side effects. Webpack will tree
// shake the CSS without this option if the issuer claims to have
// no side-effects.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
test: regexCssGlobal,
use: [
require.resolve('../../../loaders/next-flight-css-dev-loader'),
...getGlobalCssLoader(ctx, lazyPostCSSInitializer),
],
}),
],
})
)
fns.push(
loader({
oneOf: [
markRemovable({
sideEffects: false,
test: regexCssModules,
use: [
require.resolve('../../../loaders/next-flight-css-dev-loader'),
...getCssModuleLoader(ctx, lazyPostCSSInitializer),
],
}),
],
})
)
} else { } else {
fns.push( fns.push(
loader({ loader({
...@@ -370,48 +467,6 @@ export const css = curry(async function css( ...@@ -370,48 +467,6 @@ export const css = curry(async function css(
}) })
) )
} }
if (ctx.experimental.appDir) {
fns.push(
loader({
oneOf: [
markRemovable({
// A global CSS import always has side effects. Webpack will tree
// shake the CSS without this option if the issuer claims to have
// no side-effects.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
test: regexCssGlobal,
issuer: {
and: [
{
or: [
{ and: [ctx.rootDirectory, /\.(js|mjs|jsx|ts|tsx)$/] },
regexClientEntry,
],
},
],
},
use: getGlobalCssLoader(ctx, lazyPostCSSInitializer),
}),
],
})
)
fns.push(
loader({
oneOf: [
markRemovable({
sideEffects: false,
test: regexCssModules,
issuer: {
and: [ctx.rootDirectory, /\.(js|mjs|jsx|ts|tsx)$/],
or: [regexClientEntry],
},
use: getCssModuleLoader(ctx, lazyPostCSSInitializer),
}),
],
})
)
} }
} }
......
...@@ -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,10 +393,13 @@ function getCssInlinedLinkTags( ...@@ -393,10 +393,13 @@ 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]
if (mod) {
for (const chunk of mod.default.chunks) {
chunks.add(chunk) chunks.add(chunk)
} }
} }
}
return [...chunks] return [...chunks]
} }
......
...@@ -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