-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
48 lines (40 loc) · 1.26 KB
/
index.js
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
const postcss = require('postcss');
const modulePathPattern = '([\'"])(@?\\w+.*?)';
const prefixPattern = '((?:.+?|\\([\\s\\S]+?\\))\\s+from\\s+)';
const matchImports = new RegExp(`^${prefixPattern}${modulePathPattern}\\2$`);
const matchOnlyImportPath = new RegExp(`^${modulePathPattern}\\1$`);
module.exports = postcss.plugin('postcss-modules-tilda', () => (root) => {
root.walk((node) => {
if (node.type === 'atrule') {
const newImports = node.name === 'import'
? updateImportAtRulePath(node.params)
: updateImports(node.params);
if (newImports) {
node.params = newImports;
}
return;
}
if (node.type === 'decl' && node.prop === 'composes') {
const newImports = updateImports(node.value);
if (newImports) {
node.value = newImports;
}
}
});
});
function updateImports(imports) {
const matches = matchImports.exec(imports);
if (!matches) {
return undefined;
}
const [, prefix, quote, path] = matches;
return `${prefix}${quote}~${path}${quote}`;
}
function updateImportAtRulePath(stringLiteral) {
const matches = matchOnlyImportPath.exec(stringLiteral);
if (!matches) {
return undefined;
}
const [, quote, path] = matches;
return `${quote}~${path}${quote}`;
}