fix(css): parse each component's CSS on its own before joining the component stylesheet

This commit is contained in:
saberzero1 committed 2026-11-26 23:20:33 +01:00
1 parent af36801547
commit c79adab53b
4 files changed
+95 -2

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Each component's CSS is parsed on its own before the component stylesheet is put together, so a missing `}` or an unclosed comment in one plugin's CSS no longer swallows the rules of every component after it, and a stray `}` no longer fails the build; a syntax error is reported with the component's name.
+13 -2
View File
@@ -25,6 +25,7 @@ import {
import { Features, transform } from "lightningcss"
import { transform as transpile } from "esbuild"
import { write } from "./helpers"
import { isolateComponentCss } from "../../util/componentCss"
/**
* Content hash for cache-busting file names (`postscript-<hash>.js`). Not a password or security
@@ -39,6 +40,8 @@ type ComponentResources = {
beforeDOMLoaded: string[]
afterDOMLoaded: string[]
componentCssStrings: Set<string>
/** Component CSS → the component that brought it, to name it in warnings. */
cssOwners: Map<string, string>
}
function getComponentResources(ctx: BuildCtx): ComponentResources {
@@ -61,9 +64,13 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
afterDOMLoaded: new Set<string>(),
}
const cssOwners = new Map<string, string>()
for (const component of allComponents) {
const { css, beforeDOMLoaded, afterDOMLoaded } = component
for (const c of normalizeResource(css)) componentResources.css.add(c)
for (const c of normalizeResource(css)) {
componentResources.css.add(c)
if (!cssOwners.has(c)) cssOwners.set(c, component.displayName ?? component.name ?? "")
}
for (const b of normalizeResource(beforeDOMLoaded)) componentResources.beforeDOMLoaded.add(b)
for (const a of normalizeResource(afterDOMLoaded)) componentResources.afterDOMLoaded.add(a)
}
@@ -73,6 +80,7 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
beforeDOMLoaded: [...componentResources.beforeDOMLoaded],
afterDOMLoaded: [...componentResources.afterDOMLoaded],
componentCssStrings: new Set(componentResources.css),
cssOwners,
}
}
@@ -436,7 +444,10 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
const cssStringToFilename = new Map<string, string>()
const componentCss = [...componentResources.componentCssStrings]
if (componentCss.length > 0) {
const wrapped = `@layer quartz-base {\n${componentCss.join("\n")}\n}`
const isolated = componentCss.map((c) =>
isolateComponentCss(c, componentResources.cssOwners.get(c)),
)
const wrapped = `@layer quartz-base {\n${isolated.join("\n")}\n}`
const minified = transform({
filename: "component.css",
code: Buffer.from(wrapped),
+44
View File
@@ -0,0 +1,44 @@
import assert from "node:assert/strict"
import test, { describe } from "node:test"
import { Features, transform } from "lightningcss"
import { isolateComponentCss } from "./componentCss"
/** The component stylesheet as ComponentResources builds it. */
const sheet = (chunks: string[]) =>
transform({
filename: "component.css",
code: Buffer.from(
`@layer quartz-base {\n${chunks.map((c) => isolateComponentCss(c, "Bad")).join("\n")}\n}`,
),
minify: true,
include: Features.MediaQueries,
}).code.toString()
describe("isolateComponentCss", () => {
const later = ".later{color:red}"
for (const [what, bad] of [
["a missing }", ".bad{color:blue"],
["an unclosed comment", ".bad{color:blue} /* note"],
["an unclosed @media", ".bad{color:blue} @media (min-width: 1px) { .x { color: red }"],
["an unclosed string", '.bad{content:"x'],
]) {
test(`${what} in one component doesn't swallow the next one's rules`, () => {
assert.match(sheet([bad, later]), /@layer quartz-base\{.*\.later\{color:red\}\}$/)
})
}
test("a stray } doesn't fail the stylesheet", () => {
assert.match(sheet([".bad{color:blue}}", later]), /\.bad\{color:#00f\}.*\.later\{color:red\}/)
})
test("balanced CSS comes out as it did before", () => {
const css = ".a{color:red;& .b{margin:0}}@media (max-width:800px){.a{display:none}}"
const raw = transform({
filename: "component.css",
code: Buffer.from(`@layer quartz-base {\n${css}\n${later}\n}`),
minify: true,
include: Features.MediaQueries,
}).code.toString()
assert.equal(sheet([css, later]), raw)
})
})
+33
View File
@@ -0,0 +1,33 @@
import { transform } from "lightningcss"
import { recordDiagnostic } from "./diagnostics"
/**
* One component's CSS, parsed on its own and printed back balanced. All components' CSS goes
* into one stylesheet: an unclosed `{`, `/*` or string in one would swallow every later
* component's rules, and a stray `}` close the shared layer (and fail the build). Parsed alone,
* the end of the chunk closes what it left open, as a stylesheet of its own would in a browser;
* a chunk that doesn't parse is printed with the rules that do, with a warning naming the
* component.
*/
export function isolateComponentCss(css: string, owner = ""): string {
const name = owner ? `component ${owner}` : "a component"
const parse = (errorRecovery: boolean) =>
transform({ filename: "component.css", code: Buffer.from(css), errorRecovery })
try {
return parse(false).code.toString()
} catch (err) {
const loc = (err as { loc?: { line: number; column: number } }).loc
recordDiagnostic({
severity: "warning",
area: "css",
message:
`The CSS of ${name} has a syntax error (${(err as Error).message}` +
`${loc ? ` at line ${loc.line}, column ${loc.column}` : ""}); the rules that parse are kept.`,
})
try {
return parse(true).code.toString()
} catch {
return ""
}
}
}