首页 > 解决方案 > 在 Gatsby JS 中中止生成特定页面

问题描述

我正在使用 Gatsby JS 基于同一个模板生成一个包含数千个页面的站点。为了生成所有这些页面,我调用了一些外部服务来获取数据来填充它们。

我的问题是,有时这些调用会失败,但可能只是 1500 页中的一页。

是否可以中止失败的特定页面的生成,因此它不会生成,并且我可以安全地重新部署其他页面而不会覆盖失败的页面?

我尝试使用onCreatePage但没有运气。

标签: gatsby

解决方案


这是我之前回答过的类似问题

是否可以中止失败的特定页面的生成,因此它不会生成

是的。你可以这样做gatsby-node.js

const path = require(`path`)
exports.createPages = ({ graphql, actions }) => {
  const { createPage, deletePage } = actions
  const template = path.resolve(`src/templates/template.js`)

  return graphql(`
    // your query
  `, { limit: 10000 }).then(result => {
    if (result.errors) {
      throw result.errors
    }

    result.data.allMarkdownRemark.edges.forEach(edge => {
    // ##### Abort page generation HERE #######
    // Find a graphQL attribute that is undefined or null only when your call fails
    // I use callSuccess as an example. It could be the frontmatter or whatever

    if (edge.callSuccess != null) { // Only generate a page when the call is successful
      createPage({
        path: `${edge.node.frontmatter.slug}`,
        component: template ,
        context: {},
      })
    }
    deletePage(page); // otherwise delete page
  })
}

我可以安全地重新部署其他人而不会覆盖失败的人吗?

这没有简单的方法。Gatsby 在每次构建时都会重新构建所有页面。我不知道检索以前版本的页面。也许有一种方法可以再次查询您的外部服务并以这种方式检索数据。


推荐阅读