Fix CSS ordering issue with HMR (#49010)

Closes #48807.

The issue seems to be introduced with recent React Float change, which isn't a real problem but a behavior change. Resources are layered by the `precedence` key and the style insertion logic can be simplified as "insert the new stylesheet right after the existing stylesheet in the same layer". When multiple stylesheets are inserted in the same render pass, their new order will be flipped.

This is a nice feature so we can always maintain the order of resources that might conflict.
This commit is contained in:
Shu Ding 2023-04-30 22:50:58 +02:00 committed by GitHub
parent 8e4888f1f6
commit 97be2e6728
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 87 additions and 30 deletions

View file

@ -10,7 +10,7 @@ export function linkGc() {
(node as HTMLLinkElement).tagName === 'LINK'
) {
const link = node as HTMLLinkElement
if (link.dataset.precedence === 'next.js') {
if (link.dataset.precedence?.startsWith('next')) {
const href = link.getAttribute('href')
if (href) {
const [resource, version] = href.split('?v=')
@ -19,7 +19,7 @@ export function linkGc() {
`link[href^="${resource}"]`
) as NodeListOf<HTMLLinkElement>
for (const otherLink of allLinks) {
if (otherLink.dataset.precedence === 'next.js') {
if (otherLink.dataset.precedence?.startsWith('next')) {
const otherHref = otherLink.getAttribute('href')
if (otherHref) {
const [, otherVersion] = otherHref.split('?v=')

View file

@ -377,23 +377,39 @@ export async function renderToHTMLOrFlight(
)
const styles = cssHrefs
? cssHrefs.map((href, index) => (
<link
rel="stylesheet"
? cssHrefs.map((href, index) => {
// In dev, Safari and Firefox will cache the resource during HMR:
// - https://github.com/vercel/next.js/issues/5860
// - https://bugs.webkit.org/show_bug.cgi?id=187726
// Because of this, we add a `?v=` query to bypass the cache during
// development. We need to also make sure that the number is always
// increasing.
href={`${assetPrefix}/_next/${href}${
const fullHref = `${assetPrefix}/_next/${href}${
process.env.NODE_ENV === 'development' ? `?v=${Date.now()}` : ''
}`}
}`
// `Precedence` is an opt-in signal for React to handle resource
// loading and deduplication, etc. It's also used as the key to sort
// resources so they will be injected in the correct order.
// During HMR, it's critical to use different `precedence` values
// for different stylesheets, so their order will be kept.
// https://github.com/facebook/react/pull/25060
const precedence = shouldPreload
? process.env.NODE_ENV === 'development'
? 'next_' + href
: 'next'
: undefined
return (
<link
rel="stylesheet"
href={fullHref}
// @ts-ignore
precedence={shouldPreload ? 'high' : undefined}
precedence={precedence}
key={index}
/>
))
)
})
: null
const Comp = interopDefault(await getComponent())
@ -454,25 +470,33 @@ export async function renderToHTMLOrFlight(
const styles = stylesheets
? stylesheets.map((href, index) => {
const fullHref = `${assetPrefix}/_next/${href}${
process.env.NODE_ENV === 'development' ? `?v=${Date.now()}` : ''
}`
ComponentMod.preloadStyle(fullHref)
return (
<link
rel="stylesheet"
// In dev, Safari and Firefox will cache the resource during HMR:
// - https://github.com/vercel/next.js/issues/5860
// - https://bugs.webkit.org/show_bug.cgi?id=187726
// Because of this, we add a `?v=` query to bypass the cache during
// development. We need to also make sure that the number is always
// increasing.
href={fullHref}
// `Precedence` is an opt-in signal for React to handle
// resource loading and deduplication, etc:
const fullHref = `${assetPrefix}/_next/${href}${
process.env.NODE_ENV === 'development' ? `?v=${Date.now()}` : ''
}`
// `Precedence` is an opt-in signal for React to handle resource
// loading and deduplication, etc. It's also used as the key to sort
// resources so they will be injected in the correct order.
// During HMR, it's critical to use different `precedence` values
// for different stylesheets, so their order will be kept.
// https://github.com/facebook/react/pull/25060
const precedence =
process.env.NODE_ENV === 'development' ? 'next_' + href : 'next'
ComponentMod.preloadStyle(fullHref)
return (
<link
rel="stylesheet"
href={fullHref}
// @ts-ignore
precedence="next.js"
precedence={precedence}
key={index}
/>
)

View file

@ -254,6 +254,39 @@ createNextDescribe(
})
if (isDev) {
it('should not affect css orders during HMR', async () => {
const filePath = 'app/ordering/page.js'
const origContent = await next.readFile(filePath)
// h1 should be red
const browser = await next.browser('/ordering')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
)
).toBe('rgb(255, 0, 0)')
try {
await next.patchFile(
filePath,
origContent.replace('<h1>Hello</h1>', '<h1>Hello!</h1>')
)
// Wait for HMR to trigger
await check(
() => browser.eval(`document.querySelector('h1').textContent`),
'Hello!'
)
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
)
).toBe('rgb(255, 0, 0)')
} finally {
await next.patchFile(filePath, origContent)
}
})
describe('multiple entries', () => {
it('should only inject the same style once if used by different layers', async () => {
const browser = await next.browser('/css/css-duplicate-2/client')
@ -272,7 +305,7 @@ createNextDescribe(
// Even if it's deduped by Float, it should still only be included once in the payload.
// There are 3 matches, one for the rendered <link>, one for float preload and one for the <link> inside flight payload.
expect(
initialHtml.match(/css-duplicate-2\/layout\.css/g).length
initialHtml.match(/css-duplicate-2\/layout\.css\?v=/g).length
).toBe(3)
})