forked from hplush/slowreader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clean-css.ts
executable file
·60 lines (49 loc) · 1.65 KB
/
clean-css.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// 1. Merge all rules with :root selector into the single rule
// in the beginning of the file
// 2. Remove unused colors from palette (as CSS Custom Properties)
// and throw and error if other CSS Custom Properties are unused.
import { lstat, readdir, readFile, writeFile } from 'node:fs/promises'
import { extname, join } from 'node:path'
import pico from 'picocolors'
import postcss from 'postcss'
import { rootsMerger } from '../postcss/roots-merger.js'
import { getVarsCleanerError, varsCleaner } from '../postcss/vars-cleaner.js'
function printError(message: string | undefined): void {
process.stderr.write(pico.red(message) + '\n')
}
async function processCss(dir: string): Promise<void> {
let items = await readdir(dir)
await Promise.all(
items.map(async name => {
let path = join(dir, name)
let stat = await lstat(path)
if (stat.isDirectory()) {
await processCss(path)
} else if (extname(name) === '.css') {
let css = await readFile(path)
try {
let fixed = await cssCleaner.process(css, {
from: path
})
await writeFile(path, fixed.css)
} catch (e) {
if (!(e instanceof Error)) {
printError(`${e}`)
} else if (e.name === 'CssSyntaxError') {
printError(e.message)
} else {
printError(e.stack)
}
process.exit(1)
}
}
})
)
}
const ASSETS = join(import.meta.dirname, '..', 'dist', 'assets')
const cssCleaner = postcss([rootsMerger, varsCleaner])
await processCss(ASSETS)
if (getVarsCleanerError()) {
printError(getVarsCleanerError())
process.exit(1)
}