-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
37 lines (32 loc) · 1.16 KB
/
index.ts
File metadata and controls
37 lines (32 loc) · 1.16 KB
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
import { PluginCreator, parse } from 'postcss';
import { extractStyles, format } from './extract.ts';
import type { PluginOptions } from './extract.ts';
export type { PluginOptions, SelectorType } from './extract.ts';
const plugin: PluginCreator<PluginOptions> = opts => {
const options: Required<PluginOptions> = {
html: opts?.html ?? '',
selector: opts?.selector ?? 'class',
styleTags: opts?.styleTags ?? false,
indent: typeof opts?.indent === 'number' && opts.indent > 0 ? opts.indent : 2
};
return {
postcssPlugin: 'postcss-inline-extract',
Once: root => {
try {
const css = format(extractStyles(options), options.indent);
const parsedRoot = parse(css);
const source = root.source;
if (source) {
parsedRoot.each(node => { node.source = source; });
}
root.removeAll();
root.append(parsedRoot.nodes);
} catch (e) {
const message = e instanceof Error ? e.message : 'Unknown error occurred';
root.error(`Failed to extract inline styles: ${message}`, { plugin: 'postcss-inline-extract' });
}
}
};
};
plugin.postcss = true;
export default plugin;