fix(css): insert styles in the same position (#11763)

This commit is contained in:
翠 / green 2023-01-26 05:34:36 +09:00 committed by GitHub
parent 568bdabffe
commit d2f13814ea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 43 additions and 1 deletions

View File

@ -347,6 +347,9 @@ const sheetsMap = new Map<
string,
HTMLStyleElement | CSSStyleSheet | undefined
>()
// 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 {
let style = sheetsMap.get(id)
@ -374,7 +377,19 @@ export function updateStyle(id: string, content: string): void {
style.setAttribute('type', 'text/css')
style.setAttribute('data-vite-dev-id', id)
style.textContent = content
document.head.appendChild(style)
if (!lastInsertedStyle) {
document.head.appendChild(style)
// reset lastInsertedStyle after async
// because dynamically imported css will be splitted into a different file
setTimeout(() => {
lastInsertedStyle = undefined
}, 0)
} else {
lastInsertedStyle.insertAdjacentElement('afterend', style)
}
lastInsertedStyle = style
} else {
style.textContent = content
}

View File

@ -21,6 +21,12 @@ test('should load dynamic import with module', async () => {
expect(await getColor('.mod')).toBe('yellow')
})
test('style order should be consistent when style tag is inserted by JS', async () => {
expect(await getColor('.order-bulk')).toBe('orange')
await page.click('.order-bulk-update')
expect(await getColor('.order-bulk')).toBe('green')
})
describe.runIf(isBuild)('build', () => {
test('should remove empty chunk', async () => {
expect(findAssetFile(/style.*\.js$/)).toBe('')

View File

@ -7,5 +7,10 @@
<p class="mod">This should be yellow</p>
<p class="dynamic-module"></p>
<p class="order-bulk">
This should be orange
<button class="order-bulk-update">change to green</button>
</p>
<script type="module" src="/main.js"></script>
<div id="app"></div>

View File

@ -1,5 +1,6 @@
import './style.css'
import './main.css'
import './order'
import('./async.css')

View File

@ -0,0 +1,3 @@
.order-bulk {
color: blue;
}

View File

@ -0,0 +1,3 @@
.order-bulk {
color: green;
}

View File

@ -0,0 +1,6 @@
import './insert' // inserts "color: orange"
import './base.css' // includes "color: blue"
document.querySelector('.order-bulk-update').addEventListener('click', () => {
import('./dynamic.css') // includes "color: green"
})

View File

@ -0,0 +1,3 @@
const style = document.createElement('style')
style.textContent = '.order-bulk { color: orange; }'
document.head.appendChild(style)