示例工程 15-tailwind-css-and-design-tokens

15-tailwind-css-and-design-tokens/demo-02-theme-tokens/tokens.ts

typescript · 1.1 KB

import fs from "node:fs";
import path from "node:path";

type Theme = Record<string, string>;

function parseBlock(css: string, selector: string): Theme {
  const index = css.indexOf(selector);
  if (index < 0) return {};
  const start = css.indexOf("{", index);
  const end = css.indexOf("}", start);
  const body = css.slice(start + 1, end);
  const theme: Theme = {};
  for (const match of body.matchAll(/--([a-z0-9-]+):\s*([^;]+);/g)) {
    const name = match[1];
    const value = match[2];
    if (name && value) theme[name] = value.trim();
  }
  return theme;
}

const file = path.join(process.cwd(), "tokens.css");
const css = fs.readFileSync(file, "utf8");
const light = parseBlock(css, "@theme");
const dark = parseBlock(css, ".dark");

console.log(
  JSON.stringify({
    evt: "smoke",
    ok:
      light["color-primary"] === "#2563eb" &&
      dark["color-primary"] === "#60a5fa" &&
      light["color-surface"] === "#ffffff" &&
      dark["color-surface"] === "#0f172a" &&
      Object.keys(light).length >= 6 &&
      Object.keys(dark).length >= 6,
    light,
    dark,
  }),
);