index.js
5.5 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
const topologicalSort = require("./topologicalSort");
const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
const VISITED_MARKER = 1;
/**
* :import('G') {}
*
* Rule
* composes: ... from 'A'
* composes: ... from 'B'
* Rule
* composes: ... from 'A'
* composes: ... from 'A'
* composes: ... from 'C'
*
* Results in:
*
* graph: {
* G: [],
* A: [],
* B: ['A'],
* C: ['A'],
* }
*/
function addImportToGraph(importId, parentId, graph, visited) {
const siblingsId = parentId + "_" + "siblings";
const visitedId = parentId + "_" + importId;
if (visited[visitedId] !== VISITED_MARKER) {
if (!Array.isArray(visited[siblingsId])) {
visited[siblingsId] = [];
}
const siblings = visited[siblingsId];
if (Array.isArray(graph[importId])) {
graph[importId] = graph[importId].concat(siblings);
} else {
graph[importId] = siblings.slice();
}
visited[visitedId] = VISITED_MARKER;
siblings.push(importId);
}
}
module.exports = (options = {}) => {
let importIndex = 0;
const createImportedName =
typeof options.createImportedName !== "function"
? (importName /*, path*/) =>
`i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
: options.createImportedName;
const failOnWrongOrder = options.failOnWrongOrder;
return {
postcssPlugin: "postcss-modules-extract-imports",
prepare() {
const graph = {};
const visited = {};
const existingImports = {};
const importDecls = {};
const imports = {};
return {
Once(root, postcss) {
// Check the existing imports order and save refs
root.walkRules((rule) => {
const matches = icssImport.exec(rule.selector);
if (matches) {
const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
const importPath = doubleQuotePath || singleQuotePath;
addImportToGraph(importPath, "root", graph, visited);
existingImports[importPath] = rule;
}
});
root.walkDecls(/^composes$/, (declaration) => {
const matches = declaration.value.match(matchImports);
if (!matches) {
return;
}
let tmpSymbols;
let [
,
/*match*/ symbols,
doubleQuotePath,
singleQuotePath,
global,
] = matches;
if (global) {
// Composing globals simply means changing these classes to wrap them in global(name)
tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
} else {
const importPath = doubleQuotePath || singleQuotePath;
let parent = declaration.parent;
let parentIndexes = "";
while (parent.type !== "root") {
parentIndexes =
parent.parent.index(parent) + "_" + parentIndexes;
parent = parent.parent;
}
const { selector } = declaration.parent;
const parentRule = `_${parentIndexes}${selector}`;
addImportToGraph(importPath, parentRule, graph, visited);
importDecls[importPath] = declaration;
imports[importPath] = imports[importPath] || {};
tmpSymbols = symbols.split(/\s+/).map((s) => {
if (!imports[importPath][s]) {
imports[importPath][s] = createImportedName(s, importPath);
}
return imports[importPath][s];
});
}
declaration.value = tmpSymbols.join(" ");
});
const importsOrder = topologicalSort(graph, failOnWrongOrder);
if (importsOrder instanceof Error) {
const importPath = importsOrder.nodes.find((importPath) =>
// eslint-disable-next-line no-prototype-builtins
importDecls.hasOwnProperty(importPath)
);
const decl = importDecls[importPath];
throw decl.error(
"Failed to resolve order of composed modules " +
importsOrder.nodes
.map((importPath) => "`" + importPath + "`")
.join(", ") +
".",
{
plugin: "postcss-modules-extract-imports",
word: "composes",
}
);
}
let lastImportRule;
importsOrder.forEach((path) => {
const importedSymbols = imports[path];
let rule = existingImports[path];
if (!rule && importedSymbols) {
rule = postcss.rule({
selector: `:import("${path}")`,
raws: { after: "\n" },
});
if (lastImportRule) {
root.insertAfter(lastImportRule, rule);
} else {
root.prepend(rule);
}
}
lastImportRule = rule;
if (!importedSymbols) {
return;
}
Object.keys(importedSymbols).forEach((importedSymbol) => {
rule.append(
postcss.decl({
value: importedSymbol,
prop: importedSymbols[importedSymbol],
raws: { before: "\n " },
})
);
});
});
},
};
},
};
};
module.exports.postcss = true;