forked from reactjs/zh-hans.react.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
257 lines (219 loc) · 7.01 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* @emails react-core
*/
'use strict';
const {resolve} = require('path');
const webpack = require('webpack');
exports.modifyWebpackConfig = ({config, stage}) => {
// See https://github.com/FormidableLabs/react-live/issues/5
config.plugin('ignore', () => new webpack.IgnorePlugin(/^(xor|props)$/));
config.merge({
resolve: {
root: resolve(__dirname, './src'),
extensions: ['', '.js', '.jsx', '.json'],
},
});
return config;
};
exports.createPages = async ({graphql, boundActionCreators}) => {
const {createPage, createRedirect} = boundActionCreators;
// Used to detect and prevent duplicate redirects
const redirectToSlugMap = {};
const blogTemplate = resolve('./src/templates/blog.js');
const communityTemplate = resolve('./src/templates/community.js');
const docsTemplate = resolve('./src/templates/docs.js');
const tutorialTemplate = resolve('./src/templates/tutorial.js');
// Redirect /index.html to root.
createRedirect({
fromPath: '/index.html',
redirectInBrowser: true,
toPath: '/',
});
const allMarkdown = await graphql(
`
{
allMarkdownRemark(limit: 1000) {
edges {
node {
fields {
redirect
slug
}
}
}
}
}
`,
);
if (allMarkdown.errors) {
console.error(allMarkdown.errors);
throw Error(allMarkdown.errors);
}
allMarkdown.data.allMarkdownRemark.edges.forEach(edge => {
const slug = edge.node.fields.slug;
if (slug === 'docs/error-decoder.html') {
// No-op so far as markdown templates go.
// Error codes are managed by a page in src/pages
// (which gets created by Gatsby during a separate phase).
} else if (
slug.includes('blog/') ||
slug.includes('community/') ||
slug.includes('contributing/') ||
slug.includes('docs/') ||
slug.includes('tutorial/') ||
slug.includes('warnings/')
) {
let template;
if (slug.includes('blog/')) {
template = blogTemplate;
} else if (slug.includes('community/')) {
template = communityTemplate;
} else if (
slug.includes('contributing/') ||
slug.includes('docs/') ||
slug.includes('warnings/')
) {
template = docsTemplate;
} else if (slug.includes('tutorial/')) {
template = tutorialTemplate;
}
const createArticlePage = path =>
createPage({
path: path,
component: template,
context: {
slug,
},
});
// Register primary URL.
createArticlePage(slug);
// Register redirects as well if the markdown specifies them.
if (edge.node.fields.redirect) {
let redirect = JSON.parse(edge.node.fields.redirect);
if (!Array.isArray(redirect)) {
redirect = [redirect];
}
redirect.forEach(fromPath => {
if (redirectToSlugMap[fromPath] != null) {
console.error(
`Duplicate redirect detected from "${fromPath}" to:\n` +
`* ${redirectToSlugMap[fromPath]}\n` +
`* ${slug}\n`,
);
process.exit(1);
}
// A leading "/" is required for redirects to work,
// But multiple leading "/" will break redirects.
// For more context see github.com/reactjs/reactjs.org/pull/194
const toPath = slug.startsWith('/') ? slug : `/${slug}`;
redirectToSlugMap[fromPath] = slug;
createRedirect({
fromPath: `/${fromPath}`,
redirectInBrowser: true,
toPath,
});
});
}
}
});
const newestBlogEntry = await graphql(
`
{
allMarkdownRemark(
limit: 1
filter: {id: {regex: "/blog/"}}
sort: {fields: [fields___date], order: DESC}
) {
edges {
node {
fields {
slug
}
}
}
}
}
`,
);
const newestBlogNode = newestBlogEntry.data.allMarkdownRemark.edges[0].node;
// Blog landing page should always show the most recent blog entry.
createRedirect({
fromPath: '/blog/',
redirectInBrowser: true,
toPath: newestBlogNode.fields.slug,
});
};
// Parse date information out of blog post filename.
const BLOG_POST_FILENAME_REGEX = /([0-9]+)\-([0-9]+)\-([0-9]+)\-(.+)\.md$/;
// Add custom fields to MarkdownRemark nodes.
exports.onCreateNode = ({node, boundActionCreators, getNode}) => {
const {createNodeField} = boundActionCreators;
switch (node.internal.type) {
case 'MarkdownRemark':
const {permalink, redirect_from} = node.frontmatter;
const {relativePath} = getNode(node.parent);
let slug = permalink;
if (!slug) {
if (relativePath.includes('blog')) {
// Blog posts don't have embedded permalinks.
// Their slugs follow a pattern: /blog/<year>/<month>/<day>/<slug>.html
// The date portion comes from the file name: <date>-<title>.md
const match = BLOG_POST_FILENAME_REGEX.exec(relativePath);
const year = match[1];
const month = match[2];
const day = match[3];
const filename = match[4];
slug = `/blog/${year}/${month}/${day}/${filename}.html`;
const date = new Date(year, month - 1, day);
// Blog posts are sorted by date and display the date in their header.
createNodeField({
node,
name: 'date',
value: date.toJSON(),
});
}
}
if (!slug) {
slug = `/${relativePath.replace('.md', '.html')}`;
// This should only happen for the partials in /content/home,
// But let's log it in case it happens for other files also.
console.warn(
`Warning: No slug found for "${relativePath}". Falling back to default "${slug}".`,
);
}
// Used to generate URL to view this content.
createNodeField({
node,
name: 'slug',
value: slug,
});
// Used to generate a GitHub edit link.
createNodeField({
node,
name: 'path',
value: relativePath,
});
// Used by createPages() above to register redirects.
createNodeField({
node,
name: 'redirect',
value: redirect_from ? JSON.stringify(redirect_from) : '',
});
return;
}
};
exports.onCreatePage = async ({page, boundActionCreators}) => {
const {createPage} = boundActionCreators;
return new Promise(resolvePromise => {
// page.matchPath is a special key that's used for matching pages only on the client.
// Explicitly wire up all error code wildcard matches to redirect to the error code page.
if (page.path.includes('docs/error-decoder.html')) {
page.matchPath = 'docs/error-decoder:path?';
page.context.slug = 'docs/error-decoder.html';
createPage(page);
}
resolvePromise();
});
};