【发布时间】:2019-12-30 13:05:52
【问题描述】:
我正在使用 Gatsby 创建一个文档站点,使用 .mdx 来管理内容。我已经配置了gatsby-node.js 并创建了模板。一切路径都可以正常工作,但是,索引页面无法从 GraphQL 查询中获取结果。我已经清除了缓存并分别重建了项目。我尝试修复Github,建议将index.js 重命名为main.js。这在 dev 上无缝运行,但在 prod 中却不行。
这是gatsby-node.js 文件:
const {createFilePath} = require(`gatsby-source-filesystem`)
const path = require(`path`)
exports.createPages = ({actions, graphql}) => {
const {createPage} = actions
const blogPostTemplate = path.resolve('src/templates/postTemplate.js')
return(graphql(`
{
allMdx {
nodes {
frontmatter {
title
}
fields {
slug
}
}
}
}
`)).then(result => {
if(result.errors) {
throw result.errors
}
const posts = result.data.allMdx.nodes
posts.forEach(post => {
createPage({
path: post.fields.slug,
component: blogPostTemplate,
context: {
slug: post.fields.slug
}
})
})
})
}
exports.onCreateNode = ({node, actions, getNode}) => {
const { createNodeField } = actions
if(node.internal.type === `Mdx`) {
const value = createFilePath({node, getNode})
createNodeField({
name: `slug`,
node,
value
})
}
}
这是postTemplate.js 文件:
import React from 'react'
import {graphql} from 'gatsby'
import {MDXRenderer} from 'gatsby-plugin-mdx'
import Layout from '../components/Layout/Layout';
export default ({data}) => {
const {body, tableOfContents, fields} = data.mdx
return (
<Layout>
{tableOfContents}
<MDXRenderer>
{body}
</MDXRenderer>
{fields}
</Layout>
)
}
export const query = graphql`
query PostBySlug($slug: String!) {
mdx (fields: {slug: {eq: $slug}}) {
body
tableOfContents
fields {
slug
}
}
}
`
任何建议都将受到高度赞赏。
【问题讨论】:
-
为什么您将
slug作为上下文变量传递给模板而不是id? -
我正在使用
slug来构建页内标题导航。
标签: javascript reactjs gatsby