Unverified Commit 97be2e67 authored by Shu Ding's avatar Shu Ding Committed by GitHub

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.
parent 8e4888f1
...@@ -10,7 +10,7 @@ export function linkGc() { ...@@ -10,7 +10,7 @@ export function linkGc() {
(node as HTMLLinkElement).tagName === 'LINK' (node as HTMLLinkElement).tagName === 'LINK'
) { ) {
const link = node as HTMLLinkElement const link = node as HTMLLinkElement
if (link.dataset.precedence === 'next.js') { if (link.dataset.precedence?.startsWith('next')) {
const href = link.getAttribute('href') const href = link.getAttribute('href')
if (href) { if (href) {
const [resource, version] = href.split('?v=') const [resource, version] = href.split('?v=')
...@@ -19,7 +19,7 @@ export function linkGc() { ...@@ -19,7 +19,7 @@ export function linkGc() {
`link[href^="${resource}"]` `link[href^="${resource}"]`
) as NodeListOf<HTMLLinkElement> ) as NodeListOf<HTMLLinkElement>
for (const otherLink of allLinks) { for (const otherLink of allLinks) {
if (otherLink.dataset.precedence === 'next.js') { if (otherLink.dataset.precedence?.startsWith('next')) {
const otherHref = otherLink.getAttribute('href') const otherHref = otherLink.getAttribute('href')
if (otherHref) { if (otherHref) {
const [, otherVersion] = otherHref.split('?v=') const [, otherVersion] = otherHref.split('?v=')
......
...@@ -377,23 +377,39 @@ export async function renderToHTMLOrFlight( ...@@ -377,23 +377,39 @@ export async function renderToHTMLOrFlight(
) )
const styles = cssHrefs const styles = cssHrefs
? cssHrefs.map((href, index) => ( ? cssHrefs.map((href, index) => {
<link // In dev, Safari and Firefox will cache the resource during HMR:
rel="stylesheet" // - https://github.com/vercel/next.js/issues/5860
// In dev, Safari and Firefox will cache the resource during HMR: // - https://bugs.webkit.org/show_bug.cgi?id=187726
// - https://github.com/vercel/next.js/issues/5860 // Because of this, we add a `?v=` query to bypass the cache during
// - https://bugs.webkit.org/show_bug.cgi?id=187726 // development. We need to also make sure that the number is always
// Because of this, we add a `?v=` query to bypass the cache during // increasing.
// development. We need to also make sure that the number is always const fullHref = `${assetPrefix}/_next/${href}${
// increasing. process.env.NODE_ENV === 'development' ? `?v=${Date.now()}` : ''
href={`${assetPrefix}/_next/${href}${ }`
process.env.NODE_ENV === 'development' ? `?v=${Date.now()}` : ''
}`} // `Precedence` is an opt-in signal for React to handle resource
// @ts-ignore // loading and deduplication, etc. It's also used as the key to sort
precedence={shouldPreload ? 'high' : undefined} // resources so they will be injected in the correct order.
key={index} // 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={precedence}
key={index}
/>
)
})
: null : null
const Comp = interopDefault(await getComponent()) const Comp = interopDefault(await getComponent())
...@@ -454,25 +470,33 @@ export async function renderToHTMLOrFlight( ...@@ -454,25 +470,33 @@ export async function renderToHTMLOrFlight(
const styles = stylesheets const styles = stylesheets
? stylesheets.map((href, index) => { ? stylesheets.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.
const fullHref = `${assetPrefix}/_next/${href}${ const fullHref = `${assetPrefix}/_next/${href}${
process.env.NODE_ENV === 'development' ? `?v=${Date.now()}` : '' 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) ComponentMod.preloadStyle(fullHref)
return ( return (
<link <link
rel="stylesheet" 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} href={fullHref}
// `Precedence` is an opt-in signal for React to handle
// resource loading and deduplication, etc:
// https://github.com/facebook/react/pull/25060
// @ts-ignore // @ts-ignore
precedence="next.js" precedence={precedence}
key={index} key={index}
/> />
) )
......
...@@ -254,6 +254,39 @@ createNextDescribe( ...@@ -254,6 +254,39 @@ createNextDescribe(
}) })
if (isDev) { 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', () => { describe('multiple entries', () => {
it('should only inject the same style once if used by different layers', async () => { it('should only inject the same style once if used by different layers', async () => {
const browser = await next.browser('/css/css-duplicate-2/client') const browser = await next.browser('/css/css-duplicate-2/client')
...@@ -272,7 +305,7 @@ createNextDescribe( ...@@ -272,7 +305,7 @@ createNextDescribe(
// Even if it's deduped by Float, it should still only be included once in the payload. // 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. // There are 3 matches, one for the rendered <link>, one for float preload and one for the <link> inside flight payload.
expect( expect(
initialHtml.match(/css-duplicate-2\/layout\.css/g).length initialHtml.match(/css-duplicate-2\/layout\.css\?v=/g).length
).toBe(3) ).toBe(3)
}) })
......
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