forked from eriklharper/postcss-nested-import
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
48 lines (43 loc) · 1.24 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 { readFileSync } = require("fs");
const resolve = require("resolve");
/**
* @type {import('postcss').PluginCreator}
*/
module.exports = () => {
return {
AtRule: {
"nested-import": (node) => {
if (
!node.params ||
typeof node.params !== "string" ||
node.params.length < 3
) {
return;
}
let id = node.params
.replace(/^(url\(\s*)?['"]?/, "")
.replace(/['"]?\s*(\))?$/, "");
let replacement;
try {
let resolvedPath = resolve.sync(id, {
basedir: process.cwd(),
extensions: [".css"],
moduleDirectory: ["web_modules", "node_modules"],
packageFilter: (pkg) => {
if (pkg.style) pkg.main = pkg.style;
else if (!pkg.main || !/\.css$/.test(pkg.main))
pkg.main = "index.css";
return pkg;
}
});
replacement = readFileSync(resolvedPath, "utf8");
} catch (error) {
throw node.error(`error reading file:\n${id}`);
}
node.replaceWith(`${node.raws.before}${replacement}`);
}
},
postcssPlugin: "postcss-nested-import"
};
};
module.exports.postcss = true;