Skip to content

Commit 0a17d55

Browse files
committed
chore(scripts): use postcss to trial scoped styles
1 parent 8ce38a4 commit 0a17d55

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

scripts/build-styles.ts

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,29 @@ import { createMarkdown } from "./utils/create-markdown";
44
import { minifyCss } from "./utils/minify-css";
55
import { toCamelCase } from "./utils/to-pascal-case";
66
import { writeTo } from "./utils/write-to";
7+
import postcss from "postcss";
8+
9+
const createScopedStyles = (props: { source: string; moduleName: string }) => {
10+
const { source, moduleName } = props;
11+
12+
return postcss([
13+
{
14+
postcssPlugin: "postcss-plugin:scoped-styles",
15+
Once(root) {
16+
root.walkRules((rule) => {
17+
rule.selectors = rule.selectors.map((selector) => {
18+
if (/^pre /.test(selector)) {
19+
selector = `pre.${moduleName}${selector.replace(/^pre /, " ")}`;
20+
} else {
21+
selector = `.${moduleName} ${selector}`;
22+
}
23+
return selector;
24+
});
25+
});
26+
},
27+
},
28+
]).process(source).css;
29+
};
730

831
export type ModuleNames = Array<{ name: string; moduleName: string }>;
932

@@ -60,10 +83,7 @@ export async function buildStyles() {
6083
);
6184
await writeTo(`src/styles/${name}.css`, css_minified);
6285

63-
const scoped_style = content
64-
.replace(/\.hljs/g, `.${moduleName} .hljs`)
65-
// adjust for first two rules being `code.hljs` not `.hljs`
66-
.replace(/\s?code\.[_0-9a-zA-Z]+\s\.hljs/g, `.${moduleName} code.hljs`);
86+
const scoped_style = createScopedStyles({ source: content, moduleName });
6787

6888
scoped_styles += scoped_style;
6989
} else {
@@ -128,6 +148,6 @@ export async function buildStyles() {
128148
"www/data/scoped-styles.css",
129149
minifyCss(scoped_styles, { removeAll: true }),
130150
);
131-
151+
132152
console.timeEnd("build styles");
133153
}

0 commit comments

Comments
 (0)