Gatsbyjs 页面生成 |最佳实践

Gatsbyjs Page generation | Best practices

我正在使用无头 WordPress 作为数据源开发 Gatsbyjs 网络。我不想在 /pages 中静态生成所有页面,而是在 im gatsby-node.js 通过 allPages / allPosts 查询映射并使用 createPage [=19] 将数据发送到 page/post 模板=].

但是我的页面有点复杂,它们似乎需要非常不同的查询 ( acf.. )

这里的最佳做法是什么?我是否应该为每个页面创建一个模板并将数据直接映射到这些模板中?

是的,您一语中的。您必须为要生成的每种类型的页面生成 templates/pages。

TL;DR

您只需要创建不同的 createPage 动作并将它们指向不同的 templates/pages。例如:

createPage({
      path: node.fields.slug,
      component: path.resolve(`./src/templates/blog-post.js`),
      context: {
        slug: node.fields.slug,
      },
    })

 createPage({
      path: node.fields.slug,
      component: path.resolve(`./src/templates/tags.js`),
      context: {
        slug: node.fields.slug,
      },
    })

长版

标准用例

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  const result = await graphql(`
    query {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `)
  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: node.fields.slug,
      component: path.resolve(`./src/templates/blog-post.js`),
      context: {
        slug: node.fields.slug,
      },
    })
  })
}

component 将定义数据可用的位置以及 template/page/component 将使用的数据。

如果您想使用不同的模板而不是 /blog-post,您需要创建另一个 createPage 操作。像这样:

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

  return graphql(`
    {
      allMarkdownRemark(limit: 1000) {
        edges {
          node {
            id
            fields {
              slug
            }
            frontmatter {
              tags
              templateKey
            }
          }
        }
      }
    }
  `).then(result => {
    if (result.errors) {
      result.errors.forEach(e => console.error(e.toString()))
      return Promise.reject(result.errors)
    }

    const posts = result.data.allMarkdownRemark.edges

    posts.forEach(edge => {
      const id = edge.node.id
      createPage({
        path: edge.node.fields.slug,
        tags: edge.node.frontmatter.tags,
        component: path.resolve(
          `src/templates/blog-post.js`
        ),
        // additional data can be passed via context
        context: {
          id,
        },
      })
    })

    // Tag pages:
    let tags = []
    // Iterate through each post, putting all found tags into `tags`
    posts.forEach(edge => {
      if (_.get(edge, `node.frontmatter.tags`)) {
        tags = tags.concat(edge.node.frontmatter.tags)
      }
    })
    // Eliminate duplicate tags
    tags = _.uniq(tags)

    // Make tag pages
    tags.forEach(tag => {
      const tagPath = `/tags/${_.kebabCase(tag)}/`

      createPage({
        path: tagPath,
        component: path.resolve(`src/templates/tags.js`),
        context: {
          tag,
        },
      })
    })
  })
}

无需详细说明它的作用或方式(如果您需要,我可以详细说明答案),重要的是您可以使用 createPage 操作来定义多少页面、数据和组件你需要。在这种情况下,blog-post.jstags.js 将在 /blog-post/postSlug/tag/tagPath 下找到。

Promise 用例

如果你有一个小网站或项目,前面的案例可能还行,但如果你的项目越来越大,那么在这么多行中查找信息就变得很困难。所以我使用创建 promises 来存储该信息。在我的 gatsby-node:

const postsBuilder = require("./src/build/postsBuilder");
const tagsBuilder = require("./src/build/tagsBuilder");

exports.createPages = async ({graphql, actions}) => {
  await Promise.all(
    [
      postBuilder(graphql, actions),
      tagsBuilder(graphql, actions)
    ]
  );
};

然后,在其中一个构建器中:

const path = require('path')

async function postsBuilder(graphql, actions) {
  const {createPage} = actions;

  const postsQuery= await graphql(`
     {
      allMarkdownRemark(limit: 1000) {
        edges {
          node {
            id
            fields {
              slug
            }
            frontmatter {
              tags
              templateKey
            }
          }
        }
      }
    }`);

  const resultForms = postsQuery.data.allMarkdownRemark.edges;

  resultForms.map(node => {
      createPage({
        path: node.node.url + '/',
        component: whateverYouNeed,
        context: {
          name: node.node.name,
          url: node.node.url
        },
      })
  });
}

module.exports = postsBuilder;

请注意,代码可以通过多种方式进行重构,只是为了展示您可以使用的另一种方法。

我认为 promise 方式更加语义化和简洁,但是您可以根据需要在每种情况下使用任何东西。

参考文献:

  1. First query
  2. Second query