-
Notifications
You must be signed in to change notification settings - Fork 5
/
gatsby-node.js
97 lines (78 loc) · 2.91 KB
/
gatsby-node.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const cheerio = require("cheerio");
const sm = require("sitemap");
const fs = require("fs");
const defaultOptions = require('./default-options');
exports.onPostBuild = async ({ graphql, pathPrefix }, pluginOptions) => {
const options = {
...defaultOptions,
...pluginOptions,
};
options.excludePaths.push("/dev-404-page/");
const allPagesQuery = await graphql(
`
{
site {
siteMetadata {
siteUrl
}
}
allSitePage {
edges {
node {
path
}
}
}
}
`
);
const siteUrl = allPagesQuery.data.site.siteMetadata.siteUrl;
const allPagePaths = allPagesQuery.data.allSitePage.edges.map(node => node.node.path);
console.log(`Generating image sitemap for ${allPagePaths.length} pages...`);
let imagesCount = 0;
let urlData = [];
allPagePaths.filter(path => options.excludePaths.indexOf(path) === -1).forEach(path => {
const filePath = path + (path.indexOf(".html") === -1 ? "index.html" : "");
const fileContent = fs.readFileSync(`${options.buildDir}${filePath}`).toString("utf8");
const pageDOM = cheerio.load(fileContent, {
// use xmlMode to read the content in <noscript> tags
// otherwise you cannot access them
xmlMode: true,
});
const pageImages = {};
// find all gatsby-image from the current page
// we have to find the parent (e.g. .gatsby-image-wrapper),
// so we can extract the alt from <img /> and all resolution
// links from the <source /> tag
pageDOM(options.gatsbyImageSelector).each(function() {
const el = cheerio(this);
const img = el.find("picture").find("img");
const alt = img.attr("alt");
const src = img.attr("src");
if (options.ignoreImagesWithoutAlt && !alt) {
return;
}
pageImages[src] = alt;
});
const pageImagesKeys = Object.keys(pageImages);
if (pageImagesKeys.length === 0) {
return;
}
imagesCount += pageImagesKeys.length;
urlData.push({
url: siteUrl + path,
img: pageImagesKeys.map(image => {
return {
url: siteUrl + image,
title: pageImages[image],
};
}),
});
});
console.log(`Creating sitemap for ${imagesCount} images.`);
const sitemap = sm.createSitemap({
urls: urlData,
});
fs.writeFileSync(`${options.buildDir}/${options.sitemapPath}`, sitemap.toString());
console.log(`Image sitemap successfully written to ${options.buildDir}/${options.sitemapPath}`);
};