0

我正在尝试从两类 .md 文件 [projects/posts] 生成页面,我在gatsby-node.js 中将与这两个文件夹相关的查询组合在一起,如下所示:

exports.createPage = ({ graphql, actions }) => {
  const { createPage } = actions
  const blogTemplate = path.resolve("./src/templates/blog-details.js")
  const projectTemplate = path.resolve("./src/templates/project-details.js")

  return graphql(`
    query {
      projects: allMarkdownRemark(
        filter: { fileAbsolutePath: { regex: "/projects/" } }
        sort: { fields: [frontmatter___date], order: DESC }
      ) {
        nodes {
          frontmatter {
            slug
            title
          }
          fileAbsolutePath
        }
      }

      posts: allMarkdownRemark(
        filter: { fileAbsolutePath: { regex: "/posts/" } }
        sort: { fields: [frontmatter___date], order: DESC }
      ) {
        nodes {
          frontmatter {
            slug
            title
          }
          fileAbsolutePath
        }
      }
    }
  `).then(result => {
    if (result.errors) {
      Promise.reject(result.errors)
    }
    console.log(result)

    const projects = result.data.projects.nodes
    const posts = result.data.posts.nodes

    console.log("starting projects page creation")
    console.log(projects)

    projects.forEach((node, index) => {
      createPage({
        path: "/projects/" + node.frontmatter.slug,
        component: projectTemplate,
        context: { slug: node.frontmatter.slug },
      })
    })

    console.log("starting posts page creation")
    console.log(posts)

    posts.forEach((node, index) => {
      const next = index === 0 ? null : posts[index - 1]
      const previous = index === nodes.length - 1 ? null : posts[index + 1]

      createPage({
        path: "/blog/" + node.frontmatter.slug,
        component: blogTemplate,
        context: {
          slug: node.frontmatter.slug,
           previous,
           next,
        },
      })
    })
  })
}

查询正在获取响应,已从 GraphiQL 验证:在此处输入图像描述

gatsby develop在创建页面时出错: 导出的查询仅对页面组件执行。您可能正在尝试在 gatsby-node.js 中创建页面,但由于某种原因失败了。 无法找到错误的确切原因。

请让我知道我在这里缺少什么,谢谢。

4

1 回答 1

0

createPages是一个异步动作。此外,您有一个错字(注意尾随的“s”)。

gatsby-node.jsAPI 列表中,您有一个onCreatePage函数 or createPages,但没有createPage

createPages应该看起来像:

const path = require("path")

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  const queryResults = await graphql(`
    query AllProducts {
      allProducts {
        nodes {
          id
          name
          price
          description
        }
      }
    }
  `)

  const productTemplate = path.resolve(`src/templates/product.js`)
  queryResults.data.allProducts.nodes.forEach(node => {
    createPage({
      path: `/products/${node.id}`,
      component: productTemplate,
      context: {
        // This time the entire product is passed down as context
        product: node,
      },
    })
  })
}

正如我所说,注意async.

于 2021-08-13T04:59:34.717 回答