剖析和字串化 CSS
如果您想將 CSS 剖析為抽象語法樹 (AST),則有兩個您可能想要考慮的解決方案
reworkcss/css
最初是為 Node.js 編寫的,但從 CDN 使用時也能正常運作。從 esm.sh
匯入時,也會自動結合 DefinitelyTyped 的類型定義。不過,需要注意的是,DefinitelyTyped 上的類型並非「非常好」,因為許多應該標記為標記聯合類型的聯合類型,只是聯合類型,這使得類型非常模糊,需要大量類型轉換。
此外,如果你想取得 AST 並產生 CSS,reworkcss/css
也提供將其產生的 AST 轉換為字串的功能。
deno_css
是專門為 Deno 使用 TypeScript 編寫的,可在 deno.land/x
上取得。
使用 reworkcss/css
的基本範例
在此範例中,我們會將一些 CSS 解析成 AST,並修改 body
規則的 background
宣告,將顏色變更為 white
。然後,我們會將修改後的 CSS AST 轉換為字串,並將其輸出到主控台
import * as css from "https://esm.sh/css@3.0.0";
import { assert } from "https://deno.land/std@0.220.0/assert/mod.ts";
declare global {
interface AbortSignal {
reason: unknown;
}
}
const ast = css.parse(`
body {
background: #eee;
color: #888;
}
`);
assert(ast.stylesheet);
const body = ast.stylesheet.rules[0] as css.Rule;
assert(body.declarations);
const background = body.declarations[0] as css.Declaration;
background.value = "white";
console.log(css.stringify(ast));
使用 deno_css
的基本範例
在此範例中,我們會將一些 CSS 解析成 AST,並將 body
規則的 background
宣告記錄到主控台。
import * as css from "https://deno.land/x/css@0.3.0/mod.ts";
const ast = css.parse(`
body {
background: #eee;
color: #888;
}
`);
const [body] = ast.stylesheet.rules;
const [background] = body.declarations;
console.log(JSON.stringify(background, undefined, " "));