Skip to content

SSR CSS injection in development #2282

@tjk

Description

@tjk

Relevant previous issues / discussion:

User-land vue-specific patch that (partially, see NOTE below) works for me (haven't seen how it hydrates yet) --

/* relevant snippet from server.js */
const cssUrls = new Set(), cssJsUrls = new Set()
function collectCssUrls(mod) {
  mod.importedModules.forEach(submod => {
    if (submod.id.match(/\?vue.*&lang\.css/)) return cssJsUrls.add(submod.url)
    if (submod.file.endsWith(".css")) return cssUrls.add(submod.url)
    if (submod.file.endsWith(".vue")) return collectCssUrls(submod)
    /* TODO include js files like routes that include other components */
    if (submod.file.match(/route/)) return collectCssUrls(submod)
  })
}
let render
if (!isProd) {
  render = (await vite.ssrLoadModule("/src/entry-server.js")).render
  const mod = await vite.moduleGraph.getModuleByUrl('/src/app.js') /* TODO replace with your entry */
  cssUrls = mod.ssrTransformResult.deps.filter(d => d.endsWith(".css"))
} else {
  render = require("./dist/server/entry-server.js").render
}
const [appHtml] = await render(url, manifest)
const devCss = [...cssUrls].map(url => {
  return `<link rel="stylesheet" type="text/css" href="${url}">`
}).join("") + [...cssJsUrls].map(url => {
  return `<script type="module" src="${url}"></script>`
}).join("")
const html = template.replace(`<!--app-html-->`, appHtml).replace(`<!--dev-css-->`, devCss)

Curious about latest thoughts on this!

NOTE: It looks like there is some non-determinism to the above... sometimes css modules are missing...

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions