Skip to content

fix(rsc): remove duplicate server css on initial render #702

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
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
17 changes: 17 additions & 0 deletions packages/plugin-rsc/e2e/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,22 @@ function defineTest(f: Fixture) {
'color',
'rgb(255, 165, 0)',
)
await expectNoDuplicateServerCss(page)
})

async function expectNoDuplicateServerCss(page: Page) {
// check only manually inserted stylesheet link exists
// (toHaveAttribute passes only when locator matches single element)
await expect(page.locator('link[rel="stylesheet"]')).toHaveAttribute(
'href',
'/test-style-server-manual.css',
)
}

test('no duplicate server css', async ({ page }) => {
await page.goto(f.url())
await waitForHydration(page)
await expectNoDuplicateServerCss(page)
})

test('adding/removing css client @js', async ({ page }) => {
Expand Down Expand Up @@ -557,6 +573,7 @@ function defineTest(f: Fixture) {
'color',
'rgb(255, 165, 0)',
)
await expectNoDuplicateServerCss(page)
})

// TODO: need a way to add/remove links on server hmr. for now, it requires a manually reload.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export function TestStyleServer() {
</div>
<link
rel="stylesheet"
href="/test.css"
href="/test-style-server-manual.css"
precedence="test-style-server-manual"
/>
<div className="test-style-server-manual">test-style-server-manual</div>
Expand Down
55 changes: 51 additions & 4 deletions packages/plugin-rsc/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -837,7 +837,8 @@ window.__vite_plugin_react_preamble_installed__ = true;
const resolvedEntry = await this.resolve(source)
assert(resolvedEntry, `[vite-rsc] failed to resolve entry '${source}'`)
code += `await import(${JSON.stringify(resolvedEntry.id)});`
// TODO: this doesn't have to wait for "vite:beforeUpdate" and should do it right after browser css import.
// server css is normally removed via `RemoveDuplicateServerCss` on useEffect.
// this also makes sure they are removed on hmr in case initial rendering failed.
code += /* js */ `
const ssrCss = document.querySelectorAll("link[rel='stylesheet']");
import.meta.hot.on("vite:beforeUpdate", () => {
Expand Down Expand Up @@ -1910,6 +1911,36 @@ export function vitePluginRscCss(
}
},
},
createVirtualPlugin(
'vite-rsc/remove-duplicate-server-css',
async function () {
// Remove duplicate css during dev due to server rendered <link> and client inline <style>
// https://github.com/remix-run/react-router/blob/166fd940e7d5df9ed005ca68e12de53b1d88324a/packages/react-router/lib/dom-export/hydrated-router.tsx#L245-L274
assert.equal(this.environment.mode, 'dev')
function removeFn() {
document
.querySelectorAll("link[rel='stylesheet']")
.forEach((node) => {
if (
node instanceof HTMLElement &&
node.dataset.precedence?.startsWith('vite-rsc/')
) {
node.remove()
}
})
}
return `\
"use client"
import React from "react";
export default function RemoveDuplicateServerCss() {
React.useEffect(() => {
(${removeFn.toString()})();
}, []);
return null;
}
`
},
),
]
}

Expand Down Expand Up @@ -1940,6 +1971,7 @@ function generateResourcesCode(depsCode: string) {
const ResourcesFn = (
React: typeof import('react'),
deps: ResolvedAssetDeps,
RemoveDuplicateServerCss?: React.FC,
) => {
return function Resources() {
return React.createElement(React.Fragment, null, [
Expand All @@ -1960,14 +1992,29 @@ function generateResourcesCode(depsCode: string) {
src: href,
}),
),
RemoveDuplicateServerCss &&
React.createElement(RemoveDuplicateServerCss, {
key: 'remove-duplicate-css',
}),
])
}
}

return `
import __vite_rsc_react__ from "react";
export const Resources = (${ResourcesFn.toString()})(__vite_rsc_react__, ${depsCode});
`
import __vite_rsc_react__ from "react";

${
config.command === 'serve'
? `import RemoveDuplicateServerCss from "virtual:vite-rsc/remove-duplicate-server-css";`
: `const RemoveDuplicateServerCss = undefined;`
}

export const Resources = (${ResourcesFn.toString()})(
__vite_rsc_react__,
${depsCode},
RemoveDuplicateServerCss,
);
`
}

export async function transformRscCssExport(options: {
Expand Down
Loading