-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgatsby-node.js
More file actions
118 lines (113 loc) · 2.86 KB
/
gatsby-node.js
File metadata and controls
118 lines (113 loc) · 2.86 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
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
const path = require('path')
// const { createFilePath } = require('gatsby-source-filesystem')
exports.onCreateNode = ({ node, getNode, actions, graphql }) => {
const { createNodeField } = actions
if (node.internal.type === 'MarkdownRemark') {
// const slug = createFilePath({
// node,
// getNode,
// })
// createNodeField({
// node,
// name: 'slug',
// value: `/content${slug}`,
// })
}
}
exports.createPages = ({ graphql, actions }) => {
const { createPage, createRedirect } = actions
return new Promise((resolve) => {
graphql(`
{
allMarkdownRemark {
totalCount
edges {
node {
frontmatter {
tags
uninqueid
category
}
}
}
}
}
`).then(({ data }) => {
const _allMarkdownRemark = data.allMarkdownRemark;
const _edges = _allMarkdownRemark.edges
const _totalCount = _allMarkdownRemark.totalCount
// 创建分页
const blogsPerPage = 10
const numPages = Math.ceil(_totalCount / blogsPerPage)
Array.from({ length: numPages }).forEach((_, i) => {
createPage({
path: i === 0 ? '/' : `/page/${i + 1}`,
component: path.resolve('./src/templates/BlogList.tsx'),
context: {
limit: blogsPerPage,
skip: i * blogsPerPage,
numPages,
currentPage: i + 1
}
})
})
// 创建单个文章页面
_edges.forEach(({ node }) => {
const frontmatter = node.frontmatter
const slug = `${frontmatter.category.toLowerCase()}-${frontmatter.uninqueid}`;
if (node.frontmatter.uninqueid) {
createPage({
path: `/content/${slug}`,
component: path.resolve('./src/templates/BlogTemplate.tsx'),
context: {
// 传递到组件中变量
uninqueid: frontmatter.uninqueid
}
})
}
})
// 创建 tag 页面
const tagsData = _edges.map(({ node }) => (node.frontmatter.tags || [])
.split(' '))
.reduce((_total, _tagsItem) => {
return _total.concat(_tagsItem)
}, [])
Array.from(new Set(tagsData)).forEach(tag => {
createPage({
path: `/tag/${tag}`,
component: path.resolve('./src/templates/TagTemplate.tsx'),
context: {
tag: `/${tag}/` // 提供正则表达式的字符串
}
})
})
// 页面重定向
createRedirect({
fromPath: '/content',
isPermanent: true,
redirectInBrowser: true,
toPath: '/',
})
createRedirect({
fromPath: '/tag',
isPermanent: true,
redirectInBrowser: true,
toPath: '/',
})
createRedirect({
fromPath: '/page/1',
isPermanent: true,
redirectInBrowser: true,
toPath: '/',
})
createRedirect({
fromPath: '/page',
isPermanent: true,
redirectInBrowser: true,
toPath: '/',
})
// 进入下一步
resolve()
})
})
}