-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
optimize-css.ts
45 lines (39 loc) · 1.27 KB
/
optimize-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
import type { Plugin } from "vite";
import { isCarbonSvelteImport, isCssFile } from "../utils";
import type { OptimizeCssOptions } from "./create-optimized-css";
import { createOptimizedCss } from "./create-optimized-css";
import { printDiff } from "./print-diff";
// Vite plugin (Rollup-compatible) to optimize CSS for Carbon Svelte components.
export const optimizeCss = (options?: OptimizeCssOptions): Plugin => {
const verbose = options?.verbose !== false;
const ids: string[] = [];
return {
name: "vite:carbon:optimize-css",
apply: "build",
enforce: "post",
transform(_, id) {
if (isCarbonSvelteImport(id)) {
ids.push(id);
}
},
async generateBundle(_, bundle) {
// Skip processing if no Carbon Svelte imports are found.
if (ids.length === 0) return;
for (const id in bundle) {
const file = bundle[id];
if (file.type === "asset" && isCssFile(id)) {
const original_css = file.source;
const optimized_css = createOptimizedCss({
...options,
source: original_css,
ids,
});
file.source = optimized_css;
if (verbose) {
printDiff({ original_css, optimized_css, id });
}
}
}
},
};
};