【发布时间】:2021-05-05 12:52:41
【问题描述】:
我正在使用 Gatsby 和 Netlify CMS 构建一个静态网站。该网站也托管在 Netlify 上。我有一个博客部分,我从降价文件中为每篇文章生成一个页面。对于我生成的每个文章页面,在构建过程中我都会收到以下警告“查询时间过长”。该网站最终会构建,但构建时间会随着我生成的页面越多而变得越来越长,所以当我开始在我的网站中包含太多文章时,我担心它会变得太长。
我正在为 netlify CMS 创建的每个 Markdown 文件生成一个页面。
您是否介意查看 gatsby-node 文件中的代码以及我在博客模板文件中使用的查询,看看我是否做错了什么可以解释构建时警告消息?
谢谢
这是我的开发环境
npmPackages:
gatsby: ^2.26.1 => 2.26.1
gatsby-image: ^2.10.0 => 2.10.0
gatsby-plugin-netlify-cms: ^4.8.0 => 4.8.0
gatsby-plugin-react-helmet: ^3.8.0 => 3.8.0
gatsby-plugin-sharp: ^2.13.0 => 2.13.0
gatsby-plugin-styled-components: ^3.9.0 => 3.9.0
gatsby-remark-images: ^3.10.0 => 3.10.0
gatsby-remark-prismjs: ^3.12.0 => 3.12.0
gatsby-source-filesystem: ^2.9.1 => 2.9.1
gatsby-transformer-remark: ^2.15.0 => 2.15.0
gatsby-transformer-sharp: ^2.11.0 => 2.11.0
npmGlobalPackages:
gatsby-cli: 2.18.0
这是我在 gatsby-node 文件中生成的帖子页面的代码
exports.createPages = async ({ actions, graphql, reporter }) => {
const { createPage } = actions
const blogPostTemplate = require.resolve(`./src/templates/blog-post.js`)
const categoryPageTemplate = require.resolve(
`./src/templates/category-page.js`
)
const uncategorizedPageTemplate = require.resolve(
`./src/templates/uncategorized.js`
)
const _ = require("lodash")
const result = await graphql(`
{
posts: allMarkdownRemark(
sort: { fields: [frontmatter___date], order: DESC }
) {
edges {
node {
id
frontmatter {
categories
}
fields {
slug
}
}
}
}
categoriesGroup: allMarkdownRemark {
group(field: frontmatter___categories) {
fieldValue
}
}
}
`)
// Handle errors
if (result.errors) {
reporter.panicOnBuild(`Error while running GraphQL query.`)
return
}
const posts = result.data.posts.edges
const categories = result.data.categoriesGroup.group
posts.forEach(({ node }, index) => {
const nextPostId = index === 0 ? null : posts[index - 1].node.id
const previousPostId =
index === posts.length - 1 ? null : posts[index + 1].node.id
createPage({
path: `blog${node.fields.slug}`,
component: blogPostTemplate,
context: {
// additional data can be passed via context
id: node.id,
index,
nextPostId
previousPostId
},
})
})
}
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({
node,
getNode,
})
createNodeField({
node,
name: `slug`,
value,
})
}
}
这是我在博客帖子模板文件中的查询,用于从 pageContext 中获取带有 id 的帖子:
export const pageQuery = graphql`
query($id: String!, $previousPostId: String, $nextPostId: String) {
markdownRemark(id: { eq: $id }) {
id
html
frontmatter {
featuredImage {
childImageSharp {
fluid(maxWidth: 1600) {
...GatsbyImageSharpFluid_withWebp_tracedSVG
}
}
}
title
description
date(formatString: "MMMM DD, YYYY")
categories
}
}
previous: markdownRemark(id: { eq: $previousPostId }) {
frontmatter {
title
}
fields {
slug
}
}
next: markdownRemark(id: { eq: $nextPostId }) {
frontmatter {
title
}
fields {
slug
}
}
}
`
【问题讨论】: