-
|
The discussion is related to this workaround #2282 (comment) about CSS injection during SSR in development After upgrading Vite from 5.4.6 to 7.2.4 the workaround stopped to work on my side because And yes, I can relate to this request #4230 (comment) as it would be really nice if Vite could provide some official solution 🙏 |
Beta Was this translation helpful? Give feedback.
Answered by
coldshine
Dec 28, 2025
Replies: 1 comment
-
|
Just in case anyone has the same issue, here's my workaround based on the solution from #2282 (comment) and which is working in Vite@7.2.4 : // server.ts
const getAppCss = (vite?: ViteDevServer, ctxModulesIds: Set<string> = new Set()) => {
let appCss = '';
const collectCssUrls = (
modules: Set<ModuleNode>,
isCss: (module: ModuleNode) => boolean,
checked: Set<string> = new Set(),
) => {
for (const module of modules) {
if (!module.id || (module.id && checked.has(module.id))) {
continue;
}
checked.add(module.id);
if (isCss(module)) {
appCss += `<link rel="stylesheet" type="text/css" href="${module.url}" data-vite-dev-initial />\n`;
}
if (module.importedModules.size) {
collectCssUrls(module.importedModules, isCss, checked);
}
}
};
if (vite) {
// collecting css from external css-files
const mainModule = vite.moduleGraph.getModuleById(resolve('/src/main.ts'));
if (mainModule) {
collectCssUrls(new Set([mainModule]), (module) => !!module.file?.endsWith('css'));
}
// collecting css from vue-components
const ctxModules: Set<ModuleNode> = new Set();
ctxModulesIds.forEach((moduleId) => {
const module = vite.moduleGraph.getModuleById(resolve(`/${moduleId}`));
if (module) {
ctxModules.add(module);
}
});
collectCssUrls(ctxModules, (module) => /\?vue&type=style/.test(module.url));
}
return appCss;
};
let html = renderer.renderToString(app, ctx);
const appCss = process.env.NODE_ENV === 'development' ? getAppCss(vite, ctx.modules) : '';
html = html.split('<!--app-css-->').join(appCss);
// App.vue
onMounted(() => {
if (import.meta.env.DEV && document.querySelectorAll(`[data-vite-dev-id]`).length) {
document.querySelectorAll(`[data-vite-dev-initial]`).forEach((element) => {
element.remove();
});
}
}) |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
coldshine
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just in case anyone has the same issue, here's my workaround based on the solution from #2282 (comment) and which is working in Vite@7.2.4 :