-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
34 lines (30 loc) · 958 Bytes
/
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
const { readFileSync, existsSync } = require('fs');
const { resolve } = require('path');
const visit = require('unist-util-visit');
const RGX = /{@import (.*?)}/;
module.exports = function() {
const unified = this;
return function transformer(tree, file) {
visit(tree, 'paragraph', node => {
if (
node.children &&
node.children[0] &&
node.children[0].type === 'text'
) {
const matches = (node.children[0].value || '').match(RGX);
if (matches && matches[1]) {
const filePath = matches[1];
const fileAbsPath = resolve(file.dirname, filePath);
if (existsSync(fileAbsPath)) {
const rawMd = readFileSync(fileAbsPath, 'utf-8');
node.children = unified.parse(rawMd);
} else {
throw new Error(
`Unable to locate @import file in path: ${fileAbsPath}!`
);
}
}
}
});
};
};