Repository navigation
Expand file tree
/
Copy pathfmImagesToRelative.js
More file actions
68 lines (60 loc) · 2.37 KB
/
Copy pathfmImagesToRelative.js
File metadata and controls
68 lines (60 loc) · 2.37 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// https://github.com/danielmahon/gatsby-remark-relative-images/blob/1d13946cb5fa54a9cfce7767cda23286d2ea8828/src/index.ts
const path = require("path");
const { defaults, isString, find } = require("lodash");
const traverse = require("traverse");
const defaultFrontmatterOptions = {
staticFolderName: "static",
include: [],
exclude: []
};
const slash = (path) => {
const isExtendedLengthPath = /^\\\\\?\\/.test(path);
if (isExtendedLengthPath) {
return path;
}
return path.replace(/\\/g, `/`);
};
const findMatchingNode = (url, files, staticFolderName) => {
const result = find(files, (file) => {
const staticPath = slash(path.join(staticFolderName, url));
return slash(path.normalize(file.absolutePath)).endsWith(staticPath);
});
if (!result) {
throw new Error(
`No matching file found for src "${url}" in static folder "${staticFolderName}". Please check static folder name and that file exists at "${staticFolderName}${url}". This error will probably cause a "GraphQLDocumentError" later in build. All converted field paths MUST resolve to a matching file in the "static" folder.`
);
}
return result;
};
module.exports = (node, getNodes, _options) => {
const options = defaults(_options, defaultFrontmatterOptions);
const files = getNodes().filter((n) => n.absolutePath);
// Only process markdown files
if (node.internal.type === `MarkdownRemark` || node.internal.type === `Mdx`) {
// Deeply iterate through frontmatter data for absolute paths
const frontmatter = { ...node.frontmatter };
traverse(frontmatter).forEach(function (value) {
if (!isString(value)) return;
if (!path.isAbsolute(value)) return;
const paths = this.path.reduce((acc, current) => {
acc.push(acc.length > 0 ? [acc, current].join(".") : current);
return acc;
}, []);
let shouldTransform = options.include.length < 1;
if (options.include.some((a) => paths.includes(a))) {
shouldTransform = true;
}
if (options.exclude.some((a) => paths.includes(a))) {
shouldTransform = false;
}
if (!shouldTransform) return;
const imageNode = findMatchingNode(value, files, options.staticFolderName);
const newValue = path.relative(
path.join(node.fileAbsolutePath, ".."),
imageNode.absolutePath
);
this.update(newValue);
});
return frontmatter;
}
};