Skip to content

Commit

Permalink
Fix link not being GC'd sometimes (#49318)
Browse files Browse the repository at this point in the history
The `app-link-gc` module should treat the link with just pathname as the
href and full URL as the same resource. This avoids duplicate styles
during HMR:

<img width="482" alt="CleanShot 2023-05-05 at 18 12 12@2x"
src="https://user-images.githubusercontent.com/3676859/236511257-af510ed2-8e21-430a-bf71-24931b10e5de.png">

[Related bug report
(internal)](https://vercel.slack.com/archives/C03KAR5DCKC/p1683295788069859).
  • Loading branch information
shuding authored May 5, 2023
1 parent 75eccf7 commit ef8fef1
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
19 changes: 16 additions & 3 deletions packages/next/src/client/app-link-gc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,22 @@ export function linkGc() {
if (href) {
const [resource, version] = href.split('?v=')
if (version) {
const allLinks = document.querySelectorAll(
`link[href^="${resource}"]`
) as NodeListOf<HTMLLinkElement>
const currentOrigin = window.location.origin
const allLinks = [
...document.querySelectorAll(
'link[href^="' + resource + '"]'
),
// It's possible that the resource is a full URL or only pathname,
// so we need to remove the alternative href as well.
...document.querySelectorAll(
'link[href^="' +
(resource.startsWith(currentOrigin)
? resource.slice(currentOrigin.length)
: currentOrigin + resource) +
'"]'
),
] as HTMLLinkElement[]

for (const otherLink of allLinks) {
if (otherLink.dataset.precedence?.startsWith('next')) {
const otherHref = otherLink.getAttribute('href')
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/app-dir/app-css/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,35 @@ createNextDescribe(
await next.patchFile(filePath, origContent)
}
})

it('should not create duplicate link tags during HMR', async () => {
const filePath = 'app/hmr/global.css'
const origContent = await next.readFile(filePath)

const browser = await next.browser('/hmr')
try {
await next.patchFile(
filePath,
origContent.replace('background: gray;', 'background: red;')
)
await check(
() =>
browser.eval(
`window.getComputedStyle(document.querySelector('body')).backgroundColor`
),
'rgb(255, 0, 0)'
)
await check(
() =>
browser.eval(
`document.querySelectorAll('link[rel="stylesheet"][href*="/page.css"]').length`
),
1
)
} finally {
await next.patchFile(filePath, origContent)
}
})
}
})

Expand Down

0 comments on commit ef8fef1

Please sign in to comment.