Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,7 @@ async function waitForSuccessfulPingInternal(
}

const sheetsMap = new Map<string, HTMLStyleElement>()
const linkSheetsMap = new Map<string, HTMLLinkElement>()

// collect existing style elements that may have been inserted during SSR
// to avoid FOUC or duplicate styles
Expand All @@ -504,13 +505,22 @@ if ('document' in globalThis) {
.forEach((el) => {
sheetsMap.set(el.getAttribute('data-vite-dev-id')!, el)
})
document
.querySelectorAll<HTMLLinkElement>(
'link[rel="stylesheet"][data-vite-dev-id]',
)
.forEach((el) => {
linkSheetsMap.set(el.getAttribute('data-vite-dev-id')!, el)
})
}

// all css imports should be inserted at the same position
// because after build it will be a single css file
let lastInsertedStyle: HTMLStyleElement | undefined

export function updateStyle(id: string, content: string): void {
if (linkSheetsMap.has(id)) return

let style = sheetsMap.get(id)
if (!style) {
style = document.createElement('style')
Expand Down Expand Up @@ -540,6 +550,19 @@ export function updateStyle(id: string, content: string): void {
}

export function removeStyle(id: string): void {
if (linkSheetsMap.has(id)) {
// re-select elements since HMR can replace links
document
.querySelectorAll<HTMLLinkElement>(
`link[rel="stylesheet"][data-vite-dev-id]`,
)
.forEach((el) => {
if (el.getAttribute('data-vite-dev-id') === id) {
el.remove()
}
})
linkSheetsMap.delete(id)
}
const style = sheetsMap.get(id)
if (style) {
document.head.removeChild(style)
Expand Down
23 changes: 23 additions & 0 deletions playground/hmr/__tests__/hmr.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1107,4 +1107,27 @@ if (!isBuild) {
await loadPromise
}, [/connected/, 'a.js'])
})

test('deduplicate server rendered link stylesheet', async () => {
await page.goto(viteTestUrl + '/css-link/index.html')
await expect.poll(() => getColor('.test-css-link')).toBe('orange')

// remove color
editFile('css-link/styles.css', (code) =>
code.replace('color: orange;', '/* removed */'),
)
await expect.poll(() => getColor('.test-css-link')).toBe('black')

// add color
editFile('css-link/styles.css', (code) =>
code.replace('/* removed */', 'color: blue;'),
)
await expect.poll(() => getColor('.test-css-link')).toBe('blue')

// // remove css import from js
editFile('css-link/main.js', (code) =>
code.replace(`import './styles.css'`, ``),
)
await expect.poll(() => getColor('.test-css-link')).toBe('black')
})
}
2 changes: 2 additions & 0 deletions playground/hmr/css-link/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<div class="test-css-link">test-css-link</div>
<script type="module" src="./main.js"></script>
5 changes: 5 additions & 0 deletions playground/hmr/css-link/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import './styles.css'

if (import.meta.hot) {
import.meta.hot.accept()
}
26 changes: 26 additions & 0 deletions playground/hmr/css-link/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import path from 'node:path'
import { type Plugin, normalizePath } from 'vite'

// use plugin to simulate server rendered css link
export function TestCssLinkPlugin(): Plugin {
return {
name: 'test-css-link',
transformIndexHtml: {
handler(_html, ctx) {
if (!ctx.filename.endsWith('/css-link/index.html')) return
return [
{
tag: 'link',
attrs: {
rel: 'stylesheet',
href: '/css-link/styles.css',
'data-vite-dev-id': normalizePath(
path.resolve(import.meta.dirname, 'styles.css'),
),
},
},
]
},
},
}
}
3 changes: 3 additions & 0 deletions playground/hmr/css-link/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.test-css-link {
color: orange;
}
2 changes: 2 additions & 0 deletions playground/hmr/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import fs from 'node:fs/promises'
import path from 'node:path'
import { defineConfig } from 'vite'
import type { Plugin } from 'vite'
import { TestCssLinkPlugin } from './css-link/plugin'

export default defineConfig({
experimental: {
Expand Down Expand Up @@ -37,6 +38,7 @@ export default defineConfig({
virtualPlugin(),
transformCountPlugin(),
watchCssDepsPlugin(),
TestCssLinkPlugin(),
],
})

Expand Down
Loading