首页 > 解决方案 > Gatsby Rewrite Slug 与 gatsby-node.js 不会改变 url

问题描述

我正在按照官方文档使用 gatsby-node.js 进行自定义 slug,但是一旦系统运行,就好像我根本没有自定义配置一样。

我可以确认使用 GraphQL 或访问网站:两者都显示文件夹结构中的 slug,而不是我以编程方式更改的那个。

我想要实现的是删除 URL 中的年份文件夹。当我在中设置断点时,gatsby-node.js我看到 createNodeField 的值设置为我的 modified newSlug。我已经删除了缓存文件夹并重新运行:没有变化。这是我确定它已执行的代码。

const { createFilePath } = require("gatsby-source-filesystem")
exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions;
  if (node.internal.type === `Mdx`) {
    const relativeFilePath = createFilePath({
      node,
      getNode,
      trailingSlash: false,
    });
    const newSlug = relativeFilePath.substring(6); // Remove the year
    const url = `/blog/${newSlug}`;
    createNodeField({
      name: `slug`,
      node,
      value: url,
    });
  }
};

我希望有,/blog/my-article但它仍然是/blog/2021/my-article,知道吗?

标签: gatsby

解决方案


显然,您似乎正在正确创建节点(至于您提供的调试信息)。我的猜测是,除了你正确地创建了新的 slug 之外,你可能没有在页面创建中应用它(createPages)。

您的新 slug 字段在field节点下创建(导致node.fields.slug),因此您的最终查询应如下所示:

const path = require("path")

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

  const result = await graphql(`
    query {
      allMdx {
        edges {
          node {
            id
            fields {
              slug
            }
          }
        }
      }
    }
  `)

  if (result.errors) {
    reporter.panicOnBuild('  ERROR: Loading "createPages" query')
  }

  const posts = result.data.allMdx.edges

  posts.forEach(({ node }, index) => {
    createPage({
      path: node.fields.slug,
      component: path.resolve(`./src/components/posts-page-layout.js`),
      context: { id: node.id },
    })
  })
}

path属性是您为动态创建的页面设置路径的位置,因此应该会生成/blog/${newSlug}.


推荐阅读