-
-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathindex.ts
More file actions
123 lines (106 loc) · 2.6 KB
/
index.ts
File metadata and controls
123 lines (106 loc) · 2.6 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import type { ChildNode, Plugin, PluginCreator, Root } from 'postcss';
import { parseImport } from './parse-import';
/** postcss-global-data plugin options */
export type pluginOptions = {
/** List of files to be used as context */
files?: Array<string>,
/** Remove nodes in a separate plugin object, this object can be added later in your list of plugins */
lateRemover?: boolean,
/** Add global CSS to the start of files, defaults to `false` */
prepend?: boolean,
};
const pluginName = 'postcss-global-data';
const creator: PluginCreator<pluginOptions> = (opts?: pluginOptions) => {
const options = Object.assign(
// Default options
{
files: [],
lateRemover: false,
prepend: false,
},
// Provided options
opts,
);
function insert(destination: Root, source: Root, set: { add: (_: ChildNode) => void }): void {
if (!options.prepend) {
source.each((node) => {
destination.append(node);
set.add(node);
});
return;
}
const nodes = Array.from(source.nodes);
nodes.reverse();
nodes.forEach((node) => {
destination.prepend(node);
set.add(node);
});
}
if (!options.lateRemover) {
return {
postcssPlugin: pluginName,
prepare(): Plugin {
const importedCSS = new Set<ChildNode>();
const importedFiles = new Set<string>();
return {
postcssPlugin: pluginName,
Once(root, postcssHelpers): void {
options.files.forEach((file) => {
const newCSS = parseImport(root, postcssHelpers, file, importedFiles);
if (!newCSS) {
return;
}
insert(root, newCSS, importedCSS);
});
},
OnceExit(): void {
importedCSS.forEach((node) => {
node.remove();
});
importedFiles.clear();
importedCSS.clear();
},
};
},
}
}
const importedCSS = new WeakSet<ChildNode>();
return {
postcssPlugin: pluginName,
plugins: [
{
postcssPlugin: pluginName,
prepare(): Plugin {
const importedFiles = new Set<string>();
return {
postcssPlugin: pluginName,
Once(root, postcssHelpers): void {
options.files.forEach((file) => {
const newCSS = parseImport(root, postcssHelpers, file, importedFiles);
if (!newCSS) {
return;
}
insert(root, newCSS, importedCSS);
});
},
OnceExit(): void {
importedFiles.clear();
},
};
},
},
{
postcssPlugin: pluginName + '/late-remover',
OnceExit(root): void {
root.each((node) => {
if (importedCSS.has(node)) {
node.remove();
}
});
},
}
]
}
};
creator.postcss = true;
export default creator;