-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgatsby-node.js
93 lines (77 loc) · 2.76 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
const {join, relative, resolve} = require("path");
const { stat, readFile, writeFile } = require('fs').promises;
const path = require("path");
const {createHash} = require("crypto");
const { sync } = require('glob');
const {createFilePath} = require("gatsby-source-filesystem");
const MD_EXTS = ['md', 'mdx'];
const postTemplate = resolve(`./src/components/Post/index.tsx`);
const layoutTemplate = resolve(`./src/components/Layout/index.tsx`);
function isBlogPost(url) {
const match = url.match(/^\/news\/(.*)$/);
return match ? Boolean(match[1]) : false;
}
exports.onCreateBabelConfig = ({actions}) => {
actions.setBabelPreset({
name: 'babel-preset-gatsby',
options: {
reactRuntime: 'automatic', // remove required import React in TSX
},
});
};
exports.onCreatePage = ({ page, actions }) => {
const { createPage, deletePage } = actions
const { componentPath } = page;
if (MD_EXTS.some(ext => componentPath.endsWith(`.${ext}`))) {
deletePage(page);
const isPost = isBlogPost(page.path);
const component = isPost ? postTemplate : layoutTemplate;
createPage({
...page,
component: `${component}?__contentFilePath=${componentPath}`,
});
}
}
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions;
if (["Mdx", "MarkdownRemark"].some(type => node.internal.type === type)) {
const value = createFilePath({ node, getNode })
createNodeField({
name: 'isPost',
node,
value: isBlogPost(value)
});
createNodeField({
name: 'contentRelativePath',
node,
value: relative(join(__dirname, 'src'), node.fileAbsolutePath || node.internal.contentFilePath)
});
createNodeField({
name: `slug`,
node,
value,
});
}
}
exports.onPostBuild = async () => {
const publicPath = path.join(__dirname, 'public');
const files = sync(`${publicPath}/**/*.{html,js}`);
const hash = createHash(`sha256`)
.update(Date.now().toString())
.digest(`hex`);
return Promise.all(
files.map(async file => {
const stats = await stat(file);
if (stats.isFile()) {
console.log(
`[onPostBuild] Replacing page-data.json references in the following files:${file}...`
);
const content = await readFile(file, 'utf8');
const result = content
.replace(/page-data.json/g, `page-data.json?${hash}`)
.replace(/app-data.json/g, `app-data.json?${hash}`);
await writeFile(file, result, 'utf8');
}
})
);
};