fix: read class lists from string literals and watch tailwind sources

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
hugocasa
2026-11-11 13:59:01 +01:00
co-authored by Claude Opus 5.5
parent ba8bb1d639
commit 7d7a67d492
2 changed files with 67 additions and 15 deletions
+26 -12
View File
@@ -267,17 +267,20 @@ function collectTailwindCandidates(dirs: string[]): string[] {
const full = path.join(dir, e.name);
if (e.isDirectory()) walk(full);
else if (TAILWIND_SCAN_EXTS.has(path.extname(e.name))) {
// Each split keeps a different set of characters that candidates may contain
// (`content-['x']` or `content-["x"]` inside the other quote, `[&>svg]:hidden`,
// classes next to markup); the compiler drops tokens that are not utilities,
// so the union is safe.
const text = fs.readFileSync(full, "utf-8");
for (const re of [/[\s"`{};]+/, /[\s'`{};=]+/, /[\s"'`{};=]+/, /[\s"'`{}<>;=]+/]) {
for (const tok of text.split(re)) {
// Svelte's `class:hidden={x}` names the utility after the directive.
if (tok) candidates.add(tok.startsWith("class:") ? tok.slice(6) : tok);
}
const add = (tok: string) => {
// Svelte's `class:hidden={x}` names the utility after the directive.
if (tok) candidates.add(tok.startsWith("class:") ? tok.slice(6) : tok);
};
// Class lists live in string literals, whose content is split on whitespace
// only, so arbitrary values keep their quotes, `=` and `>`
// (`data-[state=open]:…`, `content-['x']`, `[&>svg]:hidden`).
for (const m of text.matchAll(/"([^"\n]*)"|'([^'\n]*)'|`([^`]*)`/g)) {
(m[1] ?? m[2] ?? m[3]).split(/\s+/).forEach(add);
}
// Classes outside literals: Svelte directives, markup.
text.split(/[\s"'`{}<>;=]+/).forEach(add);
// The compiler drops tokens that are not utilities, so over-collecting is safe.
}
}
};
@@ -415,17 +418,25 @@ function createTailwindPlugin(appDir: string, sharedUiDir?: string): any {
: compiler.root
? [compiler.root]
: dirs.map((base) => ({ base, pattern: "**/*" }));
// Tailwind 4.0 names the `@source` entries `globs` and has no negation.
const legacy = !compiler.sources;
const scanner = new kit.Scanner({
sources: [
...roots.map((r: any) => ({ ...r, negated: false })),
// `app dev` writes the previous bundle there; scanning it would
// generate a rule for every word in the bundled dependencies.
{ base: appDir, pattern: "dist/**", negated: true },
...(compiler.sources ?? []),
...(legacy ? [] : [{ base: appDir, pattern: "dist/**", negated: true }]),
...(legacy
? (compiler.globs ?? []).map((g: any) => ({ ...g, negated: false }))
: compiler.sources),
],
});
previousDeps.set(args.path, [...watchFiles]);
return result(compiler.build(scanner.scan()));
const css = compiler.build(scanner.scan());
// Files only an `@source` reaches are not in esbuild's graph; watching them
// makes `app dev` rebuild when their classes change.
for (const f of scanner.files ?? []) watchFiles.add(f);
return result(css);
}
const compiler = await kit.compile(source, {
@@ -446,6 +457,9 @@ function createTailwindPlugin(appDir: string, sharedUiDir?: string): any {
platform: "node",
format: "cjs",
packages: "external",
// CJS output has no import.meta; configs reading files beside them use
// its url. Modules the entry imports see the entry's url too.
define: { "import.meta.url": JSON.stringify(pathToFileURL(p).href) },
write: false,
metafile: true,
logLevel: "silent",
+41 -3
View File
@@ -28,7 +28,7 @@ beforeAll(() => {
write("f/demo.raw_app/index.css", `@import "/ui/theme.css";\n`);
write(
"f/demo.raw_app/index.tsx",
`import "./index.css";\nimport { cls } from "/ui/button";\nconsole.log(cls, "bg-from-app [&>svg]:hidden", "before:content-['x']", '[&>p]:block');\n`,
`import "./index.css";\nimport { cls } from "/ui/button";\nconsole.log(cls, "bg-from-app [&>svg]:hidden", "before:content-['x']", '[&>p]:block data-[s=o]:flex');\n`,
);
const pkg = "f/demo.raw_app/node_modules/tailwindcss";
write(
@@ -46,12 +46,40 @@ beforeAll(() => {
const tw = await loadStylesheet("tailwindcss", ui.base);
return {
build: (candidates) =>
tw.content + ["bg-from-app", "bg-from-ui", "[&>svg]:hidden", "before:content-['x']", "[&>p]:block"]
tw.content + ["bg-from-app", "bg-from-ui", "[&>svg]:hidden", "before:content-['x']", "[&>p]:block", "data-[s=o]:flex"]
.filter((c) => candidates.includes(c))
.map((c) => ".hit-" + c.replace(/\\W/g, "_") + " { color: red; }").join("\\n"),
};
}\n`,
);
// An app that also has Tailwind's own toolchain, which must take precedence.
write("f/official.raw_app/package.json", `{"name":"official"}`);
write("f/official.raw_app/index.css", `@import "tailwindcss";\n`);
write("f/official.raw_app/index.tsx", `import "./index.css";\n`);
const nm = "f/official.raw_app/node_modules/@tailwindcss";
write(
`${nm}/node/package.json`,
JSON.stringify({ name: "@tailwindcss/node", exports: { ".": "./index.mjs", "./require-cache": "./rc.mjs" } }),
);
write(
`${nm}/node/index.mjs`,
`export async function compile() {
return { root: null, sources: [], build: (c) => c.map((x) => "." + x + " { color: red; }").join("\\n") };
}\n`,
);
write(`${nm}/node/rc.mjs`, `export function clearRequireCache() {}\n`);
write(`${nm}/oxide/package.json`, JSON.stringify({ name: "@tailwindcss/oxide", main: "./index.mjs" }));
write(
`${nm}/oxide/index.mjs`,
`export class Scanner {
constructor({ sources }) { this.sources = sources; }
get files() { return []; }
scan() {
return this.sources.filter((s) => !s.negated)
.map((s) => (s.base.endsWith("ui") ? "scanned-ui" : "scanned-app"));
}
}\n`,
);
process.chdir(path.join(root, "f/demo.raw_app"));
});
@@ -68,8 +96,18 @@ test("tailwind stylesheets compile with the app's tailwindcss over app and ui/ s
sharedUiDir: path.join(root, "ui"),
});
expect(css).toContain("tailwind-entry");
for (const hit of ["bg_from_app", "bg_from_ui", "___svg__hidden", "before_content___x__", "___p__block"]) {
for (const hit of ["bg_from_app", "bg_from_ui", "___svg__hidden", "before_content___x__", "___p__block", "data__s_o__flex"]) {
expect(css).toContain(`.hit-${hit}`);
}
expect(css).not.toContain("@theme");
});
test("an app with @tailwindcss/node and oxide is compiled by them over app and ui/", async () => {
const { css } = await createBundle({
entryPoint: path.join(root, "f/official.raw_app/index.tsx"),
minify: false,
sharedUiDir: path.join(root, "ui"),
});
expect(css).toContain(".scanned-app");
expect(css).toContain(".scanned-ui");
});