在gatsby-node.js
中使用多个createPage
路由时,我当前遇到了一个问题。我正在尝试将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
}
})
})
}
发布于 2019-09-01 19:58:56
同一个接口(createPages
)不能定义两次。在一个函数中完成它,特别是因为您可以将其全部放入一个查询中。
这段代码显然是未经测试的,但应该可以工作:
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。
https://stackoverflow.com/questions/57748844
复制相似问题