gpt4 book ai didi

GatsbyJS - 如何使用 createPages 设置 gatsby-node.ts?

转载 作者:行者123 更新时间:2023-12-05 03:21:34 27 4
gpt4 key购买 nike

我正在将我的 Gatsby 站点迁移到 typescript 并遵循 official guide将 gatsby-node.js 更新为 .ts 文件。 js 文件工作正常,但 ts 文件不行。唯一的区别是:

  1. exports.createPages 更改为 export const sourceNodes: GatsbyNode["createPages"]
  2. import type { GatsbyNode } from "gatsby" 添加在顶部

这是不起作用的 gatsby-node.ts。

import type { GatsbyNode } from "gatsby"
import path from "path"

export const sourceNodes: GatsbyNode["createPages"] = async ({ graphql, actions, reporter }) => {
const { createPage } = actions
const result:any = await graphql(`
query {
allMdx {
edges {
node {
id
slug
}
}
}
}
`)
if (result.errors) {
reporter.panicOnBuild('🚨 ERROR: Loading "createPages" query')
}

const posts = result.data?.allMdx.edges

posts.forEach(({ node }) => {
createPage({
path: `/work/${node.slug}`,
component: path.resolve(`./src/components/works-layout.tsx`),
context: { id: node.id },
})
})
}

以及有效的 gatsby-node.js:

import path from "path"

exports.createPages = async ({ graphql, actions, reporter }) => {
const { createPage } = actions
const result = await graphql(`
query {
allMdx {
edges {
node {
id
slug
}
}
}
}
`)
if (result.errors) {
reporter.panicOnBuild('🚨 ERROR: Loading "createPages" query')
}

const posts = result.data.allMdx.edges
posts.forEach(({ node }) => {
createPage({
path: `/work/${node.slug}`,
component: path.resolve(`./src/components/works-layout.tsx`),
context: { id: node.id },
})
})
}

这里是错误的编译报告:

warn The GraphQL query in the non-page component
"/Users/cindyho/portfolio/src/components/works-layout.tsx" will not be run.
Exported queries are only executed for Page components. It's possible you're
trying to create pages in your gatsby-node.js and that's failing for some
reason.

If the failing component(s) is a regular component and not intended to be a page
component, you generally want to use a <StaticQuery>
(https://gatsbyjs.com/docs/static-query)
instead of exporting a page query.

If you're more experienced with GraphQL, you can also export GraphQL
fragments from components and compose the fragments in the Page component
query and pass data down into the child component —
https://graphql.org/learn/queries/#fragments

最佳答案

您必须将 exports.createPages = () => {} 转换为 export const createPages = () => {}

当前您有 export const sourceNodes,其中不会调用 createPage 操作。它必须发生在 createPages 生命周期中。

关于GatsbyJS - 如何使用 createPages 设置 gatsby-node.ts?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72936382/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com