Skip to content

Commit

Permalink
Fix duplicate CSS in dev mode (#4157)
Browse files Browse the repository at this point in the history
* fix(hmr): remove SSR styles once HMR styles are injected

* refactor: remove data-astro-injected tag

* chore: add changeset

Co-authored-by: Nate Moore <[email protected]>
  • Loading branch information
natemoo-re and natemoo-re authored Aug 5, 2022
1 parent 29da99c commit 0257438
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 29 deletions.
5 changes: 5 additions & 0 deletions .changeset/large-beds-cheer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fix duplicated CSS when using HMR
8 changes: 2 additions & 6 deletions packages/astro/src/core/render/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,7 @@ export async function render(
links.add({
props: {
rel: 'stylesheet',
href,
'data-astro-injected': true,
href
},
children: '',
});
Expand All @@ -162,15 +161,12 @@ export async function render(
props: {
type: 'module',
src: url,
'data-astro-injected': true,
},
children: '',
});
// But we still want to inject the styles to avoid FOUC
styles.add({
props: {
'data-astro-injected': url,
},
props: {},
children: content,
});
});
Expand Down
47 changes: 33 additions & 14 deletions packages/astro/src/runtime/client/hmr.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
/// <reference types="vite/client" />

if (import.meta.hot) {
import.meta.hot.on('vite:beforeUpdate', async (payload) => {
for (const file of payload.updates) {
if (
file.acceptedPath.includes('svelte&type=style') ||
file.acceptedPath.includes('astro&type=style')
) {
// This will only be called after the svelte component has hydrated in the browser.
// At this point Vite is tracking component style updates, we need to remove
// styles injected by Astro for the component in favor of Vite's internal HMR.
const injectedStyle = document.querySelector(
`style[data-astro-injected="${file.acceptedPath}"]`
);
if (injectedStyle) {
injectedStyle.parentElement?.removeChild(injectedStyle);
// Vite injects `<style type="text/css">` for ESM imports of styles
// but Astro also SSRs with `<style>` blocks. This MutationObserver
// removes any duplicates as soon as they are hydrated client-side.
const injectedStyles = getInjectedStyles();
const mo = new MutationObserver((records) => {
for (const record of records) {
for (const node of record.addedNodes) {
if (isViteInjectedStyle(node)) {
injectedStyles.get(node.innerHTML.trim())?.remove();
}
}
}
});
mo.observe(document.documentElement, { subtree: true, childList: true });

// Vue `link` styles need to be manually refreshed in Firefox
import.meta.hot.on('vite:beforeUpdate', async (payload) => {
for (const file of payload.updates) {
if (file.acceptedPath.includes('vue&type=style')) {
const link = document.querySelector(`link[href="${file.acceptedPath}"]`);
if (link) {
Expand All @@ -25,3 +28,19 @@ if (import.meta.hot) {
}
});
}

function getInjectedStyles() {
const injectedStyles = new Map<string, Element>();
document.querySelectorAll<HTMLStyleElement>('style').forEach((el) => {
injectedStyles.set(el.innerHTML.trim(), el);
});
return injectedStyles;
}

function isStyle(node: Node): node is HTMLStyleElement {
return node.nodeType === node.ELEMENT_NODE && (node as Element).tagName.toLowerCase() === 'style';
}

function isViteInjectedStyle(node: Node): node is HTMLStyleElement {
return isStyle(node) && node.getAttribute('type') === 'text/css';
}
10 changes: 5 additions & 5 deletions packages/astro/test/0-css.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -298,15 +298,15 @@ describe('CSS', function () {
});

it('resolves ESM style imports', async () => {
const allInjectedStyles = $('style[data-astro-injected]').text().replace(/\s*/g, '');
const allInjectedStyles = $('style').text().replace(/\s*/g, '');

expect(allInjectedStyles, 'styles/imported-url.css').to.contain('.imported{');
expect(allInjectedStyles, 'styles/imported-url.sass').to.contain('.imported-sass{');
expect(allInjectedStyles, 'styles/imported-url.scss').to.contain('.imported-scss{');
});

it('resolves Astro styles', async () => {
const allInjectedStyles = $('style[data-astro-injected]').text();
const allInjectedStyles = $('style').text();

expect(allInjectedStyles).to.contain('.linked-css:where(.astro-');
expect(allInjectedStyles).to.contain('.linked-sass:where(.astro-');
Expand All @@ -325,15 +325,15 @@ describe('CSS', function () {
expect((await fixture.fetch(href)).status, style).to.equal(200);
}

const allInjectedStyles = $('style[data-astro-injected]').text().replace(/\s*/g, '');
const allInjectedStyles = $('style').text().replace(/\s*/g, '');

expect(allInjectedStyles).to.contain('.react-title{');
expect(allInjectedStyles).to.contain('.react-sass-title{');
expect(allInjectedStyles).to.contain('.react-scss-title{');
});

it('resolves CSS from Svelte', async () => {
const allInjectedStyles = $('style[data-astro-injected]').text();
const allInjectedStyles = $('style').text();

expect(allInjectedStyles).to.contain('.svelte-css');
expect(allInjectedStyles).to.contain('.svelte-sass');
Expand All @@ -347,7 +347,7 @@ describe('CSS', function () {
expect((await fixture.fetch(href)).status, style).to.equal(200);
}

const allInjectedStyles = $('style[data-astro-injected]').text().replace(/\s*/g, '');
const allInjectedStyles = $('style').text().replace(/\s*/g, '');

expect(allInjectedStyles).to.contain('.vue-css{');
expect(allInjectedStyles).to.contain('.vue-sass{');
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/test/astro-markdown-css.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ describe('Imported markdown CSS', function () {
expect(importedAstroComponent?.name).to.equal('h2');
const cssClass = $(importedAstroComponent).attr('class')?.split(/\s+/)?.[0];

const allInjectedStyles = $('style[data-astro-injected]').text().replace(/\s*/g, '');
const allInjectedStyles = $('style').text().replace(/\s*/g, '');
expect(allInjectedStyles).to.include(`h2:where(.${cssClass}){color:#00f}`);
});
});
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/test/astro-partial-html.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe('Partial HTML', async () => {
expect(html).to.match(/^<!DOCTYPE html/);

// test 2: correct CSS present
const allInjectedStyles = $('style[data-astro-injected]').text();
const allInjectedStyles = $('style').text();
expect(allInjectedStyles).to.match(/\:where\(\.astro-[^{]+{color:red}/);
});

Expand All @@ -37,7 +37,7 @@ describe('Partial HTML', async () => {
expect(html).to.match(/^<!DOCTYPE html/);

// test 2: link tag present
const allInjectedStyles = $('style[data-astro-injected]').text().replace(/\s*/g, '');
const allInjectedStyles = $('style').text().replace(/\s*/g, '');
expect(allInjectedStyles).to.match(/h1{color:red;}/);
});

Expand Down
2 changes: 1 addition & 1 deletion packages/astro/test/component-library.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ describe('Component Libraries', () => {
const $ = cheerioLoad(html);

// Most styles are inlined in a <style> block in the dev server
const allInjectedStyles = $('style[data-astro-injected]').text().replace(/\s*/g, '');
const allInjectedStyles = $('style').text().replace(/\s*/g, '');
if (expected.test(allInjectedStyles)) {
return true;
}
Expand Down

0 comments on commit 0257438

Please sign in to comment.