node.js - 如何在 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
}
})
})
}
解决方案
您不能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
}
})
})
}
nodes
是edges.node
有效语法的快捷方式。是查询名称之前的shopify:
别名。不需要使用path
,也可以使用require.resolve
。async/await 语法更适合阅读 IMO。
推荐阅读
- c# - API 入口点无法识别 JSON (TypeScript) 的元组数组
- sql - SQL Server 从自定义分隔文本创建行
- java - Spring @Sql 注释在 UTC 中插入 MySQL 时间戳
- azure-devops - Release.Environments.{Stage}.Status 始终为“InProgress”
- python - 从文件 Python 重新加载函数后,仍然使用旧版本
- javascript - 对 Jest 测试文件进行 linting 时,eslint 会抛出 `no-undef` 错误
- sails.js - Sails.js find 不能与 or 和 select 一起使用
- sql - 如何修复 postgres 上的“SQLSTATE [42883]:未定义函数:7 错误”?
- r - 获得两个值之间成对最大值的矩阵的有效方法
- android - HERE 地图:Android N 中 setLocale 后 RouteOptions 的语言保持系统语言