Skip to content

Commit 94e2189

Browse files
committed
simplified version of the parser plugin
1 parent f646e47 commit 94e2189

File tree

1 file changed

+23
-45
lines changed

1 file changed

+23
-45
lines changed

src/parser.js

Lines changed: 23 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,38 @@
11
import { plugin } from 'postcss';
2+
import forEach from 'lodash.foreach';
23
import replaceSymbols from 'icss-replace-symbols';
3-
44
const importRegexp = /^:import\((.+)\)$/;
5+
const exportRegexp = /^:export$/;
56

6-
export default plugin('parser', function parser(opts = {}) {
7-
const exportTokens = {};
8-
const translations = {};
9-
10-
const fetchImport = (importNode, relativeTo, depNr) => {
11-
const file = importNode.selector.match(importRegexp)[1];
12-
const depTrace = opts.trace + String.fromCharCode(depNr);
13-
const exports = opts.fetch(file, opts.filename, depTrace);
14-
15-
importNode.each(decl => {
16-
if (decl.type === 'decl') {
17-
translations[decl.prop] = exports[decl.value];
18-
}
19-
});
20-
21-
importNode.removeSelf();
22-
};
7+
/**
8+
* @param {function} options.fetch
9+
* @return {function}
10+
*/
11+
export default plugin('parser', function parser({ fetch } = {}) {
12+
return css => {
13+
// https://github.com/postcss/postcss/blob/master/docs/api.md#inputfile
14+
const file = css.source.input.file;
15+
const translations = {};
16+
const exportTokens = {};
2317

24-
const fetchAllImports = css => {
25-
let imports = 0;
18+
css.walkRules(importRegexp, rule => {
19+
const exports = fetch(RegExp.$1, file);
2620

27-
css.each(node => {
28-
if (node.type === 'rule' && node.selector.match(importRegexp)) {
29-
fetchImport(node, css.source.input.from, imports++);
30-
}
21+
rule.walkDecls(decl => translations[decl.prop] = exports[decl.value]);
22+
rule.remove();
3123
});
32-
};
33-
34-
const linkImportedSymbols = css => replaceSymbols(css, translations);
3524

36-
const handleExport = exportNode => {
37-
exportNode.each(decl => {
38-
if (decl.type === 'decl') {
39-
Object.keys(translations).forEach(translation => {
40-
decl.value = decl.value.replace(translation, translations[translation]);
41-
});
25+
replaceSymbols(css, translations);
4226

27+
css.walkRules(exportRegexp, rule => {
28+
rule.walkDecls(decl => {
29+
forEach(translations, (value, key) => decl.value = decl.value.replace(key, value));
4330
exportTokens[decl.prop] = decl.value;
44-
}
45-
});
31+
});
4632

47-
exportNode.removeSelf();
48-
};
49-
50-
const extractExports = css => css.each(node => {
51-
if (node.type === 'rule' && node.selector === ':export') handleExport(node);
52-
});
33+
rule.remove();
34+
});
5335

54-
return css => {
55-
fetchAllImports(css);
56-
linkImportedSymbols(css);
57-
extractExports(css);
5836
css.tokens = exportTokens;
5937
};
6038
});

0 commit comments

Comments
 (0)