gatsby - 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
,知道吗?
解决方案
显然,您似乎正在正确创建节点(至于您提供的调试信息)。我的猜测是,除了你正确地创建了新的 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}
.
推荐阅读
- php - 如何配置 PhpMyAdmin 以防止用户修改 `phpmyadmin` 表中的其他用户设置?
- assembly - 8086 组件中的简单斐波那契打印机
- javascript - 无法运行javascript代码
- android - 无法解决:com.google.android.gms:play-services-ads:15.0.1
- javascript - SAPUI5:如何重置/清除 TextArea oder Date-Field
- ms-access - 如何将 MS Access 中的日期选择器默认为当天的 0hrs 0min 0sec?
- c - fork 进程是 C 中多线程的一个例子吗?
- android - 如何将两个形状组合成可绘制的?
- reactjs - Recharts PieChart - 数组或迭代器中的每个孩子都应该有一个唯一的“关键”道具
- python-2.7 - 由于 NoneType 错误,Matplotlib 动画失败?