1 回答
TA贡献1111条经验 获得超0个赞
你module.exports.createPages用第二个覆盖了你的第一个gatsby-node
const path = require('path');
const { createFilePath } = require('gatsby-source-filesystem');
// CREAT SLUGS FOR .MD PAGES
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions;
if (node.internal.type === 'MarkdownRemark') {
const slug = createFilePath({ node, getNode, basePath: 'pages' });
createNodeField({
node,
name: 'slug',
value: slug,
});
}
};
// DYNAMICALLY CREATE PAGES FOR EACH POST
module.exports.createPages = async ({ graphql, actions, reporter }) => {
const { createPage } = actions;
const result = await graphql(`
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
`);
// Handle errors
if (result.errors) {
reporter.panicOnBuild('Error while running GraphQL query.');
return;
}
// Create the pages for each markdown file
const postTemplate = path.resolve('src/templates/post.js');
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
component: postTemplate,
path: `${node.fields.slug}`,
context: {
slug: node.fields.slug,
},
});
});
// PAGINATION FOR BLOG POSTS
const postsResult = await graphql(
`
{
allMarkdownRemark(
sort: { fields: [frontmatter___date], order: DESC }
limit: 1000
) {
edges {
node {
fields {
slug
}
}
}
}
}
`
);
if (postsResult.errors) {
reporter.panicOnBuild('Error while running GraphQL query.');
return;
}
// Create blog-list pages
const posts = postsResult.data.allMarkdownRemark.edges;
const postsPerPage = 3;
const numPages = Math.ceil(posts.length / postsPerPage);
Array.from({ length: numPages }).forEach((_, i) => {
createPage({
path: i === 0 ? '/posts' : `/posts/${i + 1}`,
component: path.resolve('./src/templates/post-list.js'),
context: {
limit: postsPerPage,
skip: i * postsPerPage,
numPages,
currentPage: i + 1,
},
});
});
};
添加回答
举报