首页 > 解决方案 > 如何在 gatsby-node.js 中使用多个 createPage 路由

问题描述

createPage我目前在使用多条路线时遇到问题gatsby-node.js。我正在尝试将 Gatsby js 与 Shopify 商业店面和另一个 CMS 用于博客文章,因此我需要一种在查看产品和查看博客文章时分别创建路线的方法。

目前,我遇到了一个错误,该错误仅在尝试查看产品详细信息页面时出现:

(EnsureResources, ) TypeError: Cannot read property 'page' of undefined

gatsby-node.js目前看起来像这样

const path = require(`path`)

// Create product page urls
exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions
  return graphql(`
    {
      allShopifyProduct {
        edges {
          node {
            handle
          }
        }
      }
    }
  `).then(result => {
    result.data.allShopifyProduct.edges.forEach(({ node }) => {
        const id = node.handle
      createPage({
        path: `/product/${id}/`,
        component: path.resolve(`./src/templates/product-page.js`),
        context: {
            id,
        },
      })
    })
  })
}

// Create blog post slug urls
exports.createPages = async ({graphql, actions}) => {
  const {createPage} = actions
  const blogTemplate = path.resolve('./src/templates/blog.js')
  const res = await graphql (`
    query {
      allContentfulBlogPost {
        edges {
          node {
            slug
          }
        }
      }
    }
  `)

  res.data.allContentfulBlogPost.edges.forEach((edge) => {
    createPage ({
      component: blogTemplate,
      path: `/blog/${edge.node.slug}`,
      context: {
        slug: edge.node.slug
      }
    })
  })
}

标签: node.jsreactjsgatsby

解决方案


您不能createPages两次定义相同的 API ( )。在一个函数中执行此操作,尤其是因为您都可以将其放入一个查询中。

这段代码显然未经测试,但应该可以工作:

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  const result = await graphql(`
    {
      shopify: allShopifyProduct {
        nodes {
          handle
        }
      }
      contentful: allContentfulBlogPost {
        nodes {
          slug
        }
      }
    }
  `)

  const shopifyTemplate = require.resolve(`./src/templates/product-page.js`)
  const contentfulTemplate = require.resolve('./src/templates/blog.js')

  if (result.errors) {
    return
  }

  result.data.shopify.nodes.forEach(product => {
    const id = product.handle

    createPage({
      path: `/product/${id}/`,
        component: shopifyTemplate,
        context: {
            id,
        },
    })
  })

  result.data.contentful.nodes.forEach(post => {
    createPage ({
      component: contentfulTemplate,
      path: `/blog/${post.slug}`,
      context: {
        slug: post.slug
      }
    })
  })
}

nodesedges.node有效语法的快捷方式。是查询名称之前的shopify:别名。不需要使用path,也可以使用require.resolve。async/await 语法更适合阅读 IMO。


推荐阅读