我正在使用 GatsbyJS 构建一个网站。我在两个不同的文件夹中有 markdown 文件:/content/collections并且/content/posts我希望 Gatsby 为每个 markdown 文件创建一个页面,并使用相应的模板(collection.js 和 post.js)。
所以我在 gatsby-node.js 文件中写了这个:
const path = require('path');
const { createFilePath } = require('gatsby-source-filesystem');
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions;
if (node.internal.type === 'MarkdownRemark') {
const longSlug = createFilePath({ node, getNode, basePath: 'content' });
const slug = longSlug.split('/');
createNodeField({
node,
name: 'slug',
value: `/${slug[slug.length - 2]}/`,
});
}
};
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const result = await graphql(`
query {
allFile(filter: {relativeDirectory: {eq: "collections"}}) {
edges {
node {
childMarkdownRemark {
fields {
slug
}
}
}
}
}
}
`);
result.data.allFile.edges.forEach(({ node }) => {
createPage({
path: node.childMarkdownRemark.fields.slug,
component: path.resolve('./src/templates/collection.js'),
context: {
slug: node.childMarkdownRemark.fields.slug,
},
});
});
};
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const result = await graphql(`
query {
allFile(filter: {relativeDirectory: {eq: "posts"}}) {
edges {
node {
childMarkdownRemark {
fields {
slug
}
}
}
}
}
}
`);
result.data.allFile.edges.forEach(({ node }) => {
createPage({
path: node.childMarkdownRemark.fields.slug,
component: path.resolve('./src/templates/post.js'),
context: {
slug: node.childMarkdownRemark.fields.slug,
},
});
});
};
认为这会起作用。它确实适用于我放入的第二种类型。(在这种情况下,它创建帖子,但不创建集合。如果我颠倒调用 createPages 的顺序,它会交换,但它永远不会创建所有这些)
芜湖不芜
相关分类