问题
I'm learning Gatsby and I wanted to use MDX for blog pages. I followed the tutorial here to programmatically create pages.
I can see them in my GraphQL, and displaying the list of all the articles is working with their title and slug, but when I click on the link to open them or type their address I have a 404 page. Do you have an idea from where it can come from?
This is my code:
gatsby-node.js:
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === "Mdx") {
const value = createFilePath({ node, getNode })
createNodeField({
name: "slug",
node,
value: `/blog${value}`,
})
}
}
gatsby-config.js:
plugins: [
{
resolve: `gatsby-plugin-mdx`,
options: {
defaultLayouts: { default: path.resolve('./src/layouts/post.js') },
extensions: [`.mdx`, `.md`],
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `posts`,
path: `${__dirname}/src/posts`
}
},
],
index.js (with the list):
<ul>
{posts.map(({ node: post }) => (
<li key={post.id}>
<Link to={post.fields.slug}>
<h2>{post.frontmatter.title}</h2>
</Link>
<p>{post.excerpt}</p>
</li>
))}
</ul>
Query in index.js
export const pageQuery = graphql`
query blogIndex {
allMdx {
edges {
node {
id
excerpt
frontmatter {
title
}
fields {
slug
}
}
}
}
}
`
The template:
<div>
<div className="content" dangerouslySetInnerHTML={{ __html: post.html }}></div>
</div>
And the query for the template:
export const pageQuery = graphql`
query BlogPostQuery($id: String) {
mdx(id: { eq: $id }) {
id
body
frontmatter {
title
}
}
}
`
I made a repo if you want to test it: https://github.com/JulSeb42/gatsby-mdx
Thanks for your answers!
回答1:
You are missing the page creation part. In your gatsby-node.js
add the following:
const path = require("path")
exports.createPages = async ({ graphql, actions, reporter }) => {
// Destructure the createPage function from the actions object
const { createPage } = actions
const result = await graphql(`
query {
allMdx {
edges {
node {
id
fields {
slug
}
}
}
}
}
`)
if (result.errors) {
reporter.panicOnBuild('🚨 ERROR: Loading "createPages" query')
}
// Create blog post pages.
const posts = result.data.allMdx.edges
// you'll call `createPage` for each result
posts.forEach(({ node }, index) => {
createPage({
// This is the slug you created before
// (or `node.frontmatter.slug`)
path: node.fields.slug,
// This component will wrap our MDX content
component: path.resolve(`./src/components/posts-page-layout.js`),
// You can use the values in this context in
// our page layout component
context: { id: node.id },
})
})
}
Regarding your other issue, it should be a separate question but, if a component is exported as default, you don't need the curly braces when importing it. In addition, you need to return a value.
来源:https://stackoverflow.com/questions/64834852/gatsby-mdx-showing-title-and-slug-but-doesnt-find-page