Skip to content

Commit a01d928

Browse files
committed
Only import files once
1 parent 41383c9 commit a01d928

File tree

3 files changed

+30
-8
lines changed

3 files changed

+30
-8
lines changed

README.md

+3
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ Node. Specify the CSS file for a module using the `style` field in
1414
module, like `@import "my-module/my-file";`. You can also require files relative
1515
to the current file using `@import "./my-file";`.
1616

17+
Note that files will only be imported once. If a file was previously imported,
18+
the `@import` for that file will be ignored after being imported the first time.
19+
1720
## Example
1821

1922
```js

example/other.css

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
@import "my-css";
2+
13
.other {
24
content: "From other.css";
35
}

index.js

+25-8
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ module.exports = reworkNPM;
77

88
function reworkNPM(dir) {
99
return function(style) {
10-
style.rules = resolveImports(dir, style);
10+
style.rules = resolveImports([], dir, style);
1111
return style;
1212
};
1313
}
@@ -17,7 +17,7 @@ function isNpmImport(path) {
1717
return !/:\/\//.test(path);
1818
}
1919

20-
function resolveImports(dir, style) {
20+
function resolveImports(included, dir, style) {
2121
dir = dir || process.cwd();
2222
dir = path.resolve(dir);
2323

@@ -26,17 +26,18 @@ function resolveImports(dir, style) {
2626
if (rule.type !== 'import') {
2727
processed.push(rule);
2828
} else {
29-
processed = processed.concat(getImport(dir, rule));
29+
var imported = getImport(included, dir, rule);
30+
processed = processed.concat(imported);
3031
}
3132
});
3233

3334
return processed;
3435
}
3536

36-
function getImport(dir, rule) {
37+
function resolveImport(dir, rule) {
3738
var name = rule.import.replace(/^\"|\"$/g, '');
3839
if (!isNpmImport(name)) {
39-
return [rule];
40+
return null;
4041
}
4142

4243
var options = {
@@ -45,13 +46,29 @@ function getImport(dir, rule) {
4546
packageFilter: processPackage
4647
};
4748

48-
var file = resolve.sync(name, options),
49-
importDir = path.dirname(file),
49+
var file = resolve.sync(name, options);
50+
return path.normalize(file);
51+
}
52+
53+
function getImport(included, dir, rule) {
54+
var file = resolveImport(dir, rule);
55+
if (!file) {
56+
return [rule];
57+
}
58+
59+
// Only include a file once
60+
if (included.indexOf(file) !== -1) {
61+
return [];
62+
}
63+
64+
included.push(file);
65+
66+
var importDir = path.dirname(file),
5067
contents = fs.readFileSync(file, 'utf8'),
5168
styles = css.parse(contents).stylesheet;
5269

5370
// Resolve imports in the imported file
54-
return resolveImports(importDir, styles);
71+
return resolveImports(included, importDir, styles);
5572
}
5673

5774
function processPackage(package) {

0 commit comments

Comments
 (0)