0

我正在尝试通过了解 Maggie Appleton 网站 (maggieappleton.com) 的运作方式来学习如何在 GatsbyJS 中构建数字花园,这是一个了不起的网站 imo。

mdx 笔记根据其性质(书籍、论文、插图或数字花园笔记)分类在不同的文件夹中。它们位于content文件夹中。

一般文件夹结构如下:

--content
  --books
  --notes
  [...]
--src
  --@aengusm
     --gatsby-theme-brain
       --components
         --BrainNote.js 
       --templates
         --Brain,js
  --components
  --fonts
  --lib
  --pages
  --stories
  --templates
    --bookTemplate.js
    --essayTemplate.js
    --illustrationTemplate.js
    --noteTemplate.js
    --paperTemplate.js       

据我了解:在 中gatsby-node.jscreatePages首先查询frontmatter 和note 的内容,并根据特定模板(在模板文件夹中找到)生成页面。

这适用于所有页面,除了数字花园的注释。在这种情况下,必须在音符之间创建双向链接,这就是 Aengus McMillin 的 gatsby-them-brain 插件发挥作用的地方。

节点首先由onCreateNode插件创建并由插件使用以创建双向链接结构。我不确定如何生成注释页面(我相信通过 中的 MDXprovider 组件BrainNote.js)。

在运行 gatsby develop 时,我面临以下问题:

warn The GraphQL query in the non-page component
"[...]/maggieappleton.com/src/templates/noteTemplate.js" will not be  
run.
warn The GraphQL query in the non-page component "[..]/maggieappleton.com/node_modules/@aengusm/gatsby-theme-brain/src/templates/brain.js" will not be run.
Exported queries are only executed for Page components. It's possible you're
trying to create pages in your gatsby-node.js and that's failing for some
reason.

If the failing component(s) is a regular component and not intended to be a page
component, you generally want to use a <StaticQuery> (https://gatsbyjs.org/docs/static-query)
instead of exporting a page query.

If you're more experienced with GraphQL, you can also export GraphQL
fragments from components and compose the fragments in the Page component
query and pass data down into the child component — https://graphql.org/learn/queries/#fragments

gatsby develop 工作正常,但从未生成注释页面。

notesQueryin似乎工作,gatsby-node.js因为笔记瓷砖正确显示在首页和数字花园页面上。但是,注释本身无法按照插件的逻辑和noteTemplate.js.

一定有我遗漏的东西,任何帮助将不胜感激!

重现步骤:

  1. https://github.com/MaggieAppleton/maggieappleton.com分叉
  2. 纱线安装
  3. 盖茨比发展

以下是gatsby-node.js内容:

const path = require('path')
const _ = require('lodash')

// const REDIRECT_SLUGS = ['slugs', 'in', 'here']

exports.createPages = ({ actions, graphql }) => {
  const { createRedirect, createPage } = actions

  //   REDIRECT_SLUGS.forEach(slug => {
  //     createRedirect({
  //       fromPath: `/${slug}`,
  //       toPath: `http://localhost:8001/${slug}`,
  //       redirectInBrowser: true,
  //       isPermanent: true,
  //     })
  //   })

  return graphql(`
    query {
      notesQuery: allMdx(
        filter: {
          frontmatter: { type: { eq: "note" }, published: { ne: false } }
        }
        sort: { order: DESC, fields: frontmatter___updated }
      ) {
        edges {
          node {
            id
            parent {
              ... on File {
                name
                sourceInstanceName
              }
            }
            excerpt(pruneLength: 250)
            fields {
              title
              slug
              updated
              growthStage
            }
          }
        }
      }

      essaysQuery: allMdx(
        filter: {
          frontmatter: { type: { eq: "essay" }, published: { ne: false } }
        }
        sort: { order: DESC, fields: frontmatter___updated }
      ) {
        edges {
          node {
            id
            parent {
              ... on File {
                name
                sourceInstanceName
              }
            }
            excerpt(pruneLength: 250)
            fields {
              title
              slug
              updated
            }
          }
        }
      }

      illustrationQuery: allMdx(
        filter: {
          frontmatter: {
            type: { eq: "illustration" }
            published: { ne: false }
          }
        }
        sort: { order: DESC, fields: frontmatter___updated }
      ) {
        edges {
          node {
            id
            parent {
              ... on File {
                name
                sourceInstanceName
              }
            }
            excerpt(pruneLength: 250)
            fields {
              title
              slug
              updated
            }
          }
        }
      }

      bookQuery: allMdx(
        filter: {
          frontmatter: { type: { eq: "book" }, published: { ne: false } }
        }
        sort: { order: DESC, fields: frontmatter___updated }
      ) {
        edges {
          node {
            id
            parent {
              ... on File {
                name
                sourceInstanceName
              }
            }
            excerpt(pruneLength: 250)
            fields {
              title
              slug
              updated
            }
          }
        }
      }

      paperQuery: allMdx(
        filter: {
          frontmatter: { type: { eq: "paper" }, published: { ne: false } }
        }
        sort: { order: DESC, fields: frontmatter___updated }
      ) {
        edges {
          node {
            id
            parent {
              ... on File {
                name
                sourceInstanceName
              }
            }
            excerpt(pruneLength: 250)
            fields {
              title
              slug
              updated
            }
          }
        }
      }
    }
  `).then(({ data, errors }) => {
    if (errors) {
      return Promise.reject(errors)
    }

    const pageRedirects = node => {
      if (node.fields.redirects) {
        node.fields.redirects.forEach(fromPath => {
          createRedirect({
            fromPath,
            toPath: node.fields.slug,
            redirectInBrowser: true,
            isPermanent: true,
          })
        })
      }
    }

    data.essaysQuery.edges.forEach(({ node }, i) => {
      const { edges } = data.essaysQuery
      const prevPage = i === 0 ? null : edges[i - 1].node
      const nextPage = i === edges.length - 1 ? null : edges[i + 1].node
      pageRedirects(node)
      createPage({
        path: node.fields.slug,
        component: path.resolve('./src/templates/essayTemplate.js'),
        context: {
          id: node.id,
          prevPage,
          nextPage,
        },
      })
    })

    data.illustrationQuery.edges.forEach(({ node }, i) => {
      const { edges } = data.illustrationQuery
      const prevPage = i === 0 ? null : edges[i - 1].node
      const nextPage = i === edges.length - 1 ? null : edges[i + 1].node

      pageRedirects(node)
      createPage({
        path: node.fields.slug,
        component: path.resolve('./src/templates/illustrationTemplate.js'),
        context: {
          id: node.id,
          prevPage,
          nextPage,
        },
      })
    })

    data.bookQuery.edges.forEach(({ node }, i) => {
      const { edges } = data.bookQuery
      const prevPage = i === 0 ? null : edges[i - 1].node
      const nextPage = i === edges.length - 1 ? null : edges[i + 1].node
      pageRedirects(node)
      createPage({
        path: node.fields.slug,
        component: path.resolve('./src/templates/bookTemplate.js'),
        context: {
          id: node.id,
          prevPage,
          nextPage,
        },
      })
    })

    data.paperQuery.edges.forEach(({ node }, i) => {
      const { edges } = data.paperQuery
      const prevPage = i === 0 ? null : edges[i - 1].node
      const nextPage = i === edges.length - 1 ? null : edges[i + 1].node
      pageRedirects(node)
      createPage({
        path: node.fields.slug,
        component: path.resolve('./src/templates/paperTemplate.js'),
        context: {
          id: node.id,
          prevPage,
          nextPage,
        },
      })
    })
  })
}

exports.onCreateWebpackConfig = ({ actions }) => {
  actions.setWebpackConfig({
    resolve: {
      modules: [path.resolve(__dirname, 'src'), 'node_modules'],
      alias: {
        'react-dom': '@hot-loader/react-dom',
        $components: path.resolve(__dirname, 'src/components'),
      },
    },
  })
}

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions

  if (
    node.internal.type === `Mdx` &&
    !_.get(node, 'frontmatter.type', []).includes('note')
  ) {
    const parent = getNode(node.parent)
    if (_.isUndefined(parent.name)) {
      return
    }
    const titleSlugged = _.join(_.drop(parent.name.split('-'), 3), '-')
    const slug =
      parent.sourceInstanceName === 'legacy'
        ? `notes/${node.frontmatter.updated
            .split('T')[0]
            .replace(/-/g, '/')}/${titleSlugged}`
        : node.frontmatter.slug || titleSlugged

    createNodeField({
      name: 'id',
      node,
      value: node.id,
    })

    createNodeField({
      name: 'published',
      node,
      value: node.frontmatter.published,
    })

    createNodeField({
      name: 'title',
      node,
      value: node.frontmatter.title,
    })

    createNodeField({
      name: 'subtitle',
      node,
      value: node.frontmatter.subtitle,
    })

    createNodeField({
      name: 'description',
      node,
      value: node.frontmatter.description,
    })

    createNodeField({
      name: 'slug',
      node,
      value: slug,
    })

    createNodeField({
      name: 'url',
      node,
      value: node.frontmatter.url,
    })

    createNodeField({
      name: 'updated',
      node,
      value: node.frontmatter.updated
        ? node.frontmatter.updated.split(' ')[0]
        : '',
    })

    createNodeField({
      name: 'cover',
      node,
      value: node.frontmatter.cover,
    })

    createNodeField({
      name: 'type',
      node,
      value: node.frontmatter.type || [],
    })

    createNodeField({
      name: 'topics',
      node,
      value: node.frontmatter.topics || [],
    })

    createNodeField({
      name: 'redirects',
      node,
      value: node.frontmatter.redirects,
    })

    createNodeField({
      name: 'redirectTo',
      node,
      value: node.frontmatter.redirectTo,
    })

    createNodeField({
      name: 'isPost',
      node,
      value: true,
    })

    createNodeField({
      name: 'growthStage',
      node,
      value: node.frontmatter.growthStage,
    })
  }
}

BrainNote.js

import React from 'react'
import { MDXProvider } from '@mdx-js/react'
import { useStaticQuery, graphql } from 'gatsby'
import 'tippy.js/animations/shift-away.css'
import Note from '../../../components/Note'
import components from '../../../components/mdx'
import { ReferenceBlock, ReferenceItem } from '../../../components/ReferenceBlock'


const BrainNote = ({ note }) => {

  //GraphQL Query
  const { site } = useStaticQuery(graphql`
    query BrainNoteStaticQuery {
      site {
        siteMetadata {
          title
          description
          author {
            name
          }
          keywords
        }
      }
    }
  `)

    //Declare the references array and the references block
  let references = []
  let referenceBlock

  // If the inbound note (eg. notes that point TO this note) is NOT null, map each inbound note's contents to a list item that links to the source and shows a preview of the HTML. This list item is assigned to the variable "references"
  //These are the notes that will show up in the references block
      // Turn this into a component
  if (note.inboundReferenceNotes != null) {
    references = note.inboundReferenceNotes.map(ref => (<ReferenceItem pageLink={ref.slug} pageTitle={ref.title} excerpt={ref.childMdx.excerpt} />))

    // If the number of inbound reference notes is longer than 0 list items, render a Reference Block.
    // Turn this into a component
    if (references.length > 0) {
      referenceBlock = <ReferenceBlock references={references} />
    }
  }

  // Declare a variable for Bidirectional Link Previews
  const bidirectionallinkpreviews = {}

  // If there are outbound reference notes (notes this note it pointing to), filter each note. Find the title, slug, and excerpt and map it to a preview component
   // Turn this into a component
  if (note.outboundReferenceNotes) {
    note.outboundReferenceNotes
      .filter(reference => !!reference.childMdx.excerpt)
      .forEach((ln, i) => {
        bidirectionallinkpreviews[ln.slug] = (
          <div style={{ padding: '1em 0.6em' }} id={ln.slug}>
            <h2 style={{ margin: '0 0 0.4em 0', fontSize: '1.66em' }}>{ln.title}</h2>
            <p>{ln.childMdx.excerpt}</p>
          </div>
        )
      })
  }

  // Decalre a variable called 'Tippy Link with Previews' and assign it to a function component. The function takes in props, and returns a standard MDX link component. It assigned the bidirectionallinkpreviews variable to a new bidirectionallinkpreviews props
  const TippyLinkWithPreviews = props => (
    <components.a
      {...props}
      bidirectionallinkpreviews={bidirectionallinkpreviews}
    />
  )

  return (
    <MDXProvider components={{...components, a: TippyLinkWithPreviews }}>
      <Note referenceBlock={referenceBlock} note={note} site={site} />
    </MDXProvider>
  )
}

export default BrainNote

Brain.js

import React from 'react'
import { graphql } from 'gatsby'
import BrainNote from '../components/BrainNote'

export default props => {
  return <BrainNote note={props.data.brainNote} />
}

export const query = graphql`
  query BrainNoteWithRefsBySlug($slug: String!) {
    site {
      ...site
    }
    brainNote(slug: { eq: $slug }) {
      slug
      title
      childMdx {
        body
        frontmatter {
          title
          updated(formatString: "MMM DD, YYYY")
          startDate(formatString: "MMM DD, YYYY")
          slug
          topics
          growthStage
        }
      }
      inboundReferenceNotes {
        title
        slug
        childMdx {
          excerpt(pruneLength: 200)
        }
      }
      outboundReferenceNotes {
        title
        slug
        childMdx {
          excerpt(pruneLength: 280)
        }
      }
    }
  }
`

noteTemplate.js

import React from 'react'
import { graphql } from 'gatsby'
import { MDXRenderer } from 'gatsby-plugin-mdx'
import SEO from 'components/SEO'
import { css } from '@emotion/core'
import Container from 'components/Container'
import Layout from '../components/Layout'
import { fonts } from '../lib/typography'
import Share from '../components/Share'
import config from '../../config/website'
import { useTheme } from 'components/Theming'
import { bpMaxSM } from '../lib/breakpoints'
import PreviousNext from '../components/PreviousNext'
// import { BacklinkItem, BacklinksSection } from '../components/BacklinksSection'

export default function Note({
  data: { site, mdx },
  pageContext: { prevPage, nextPage },
}) {
  const updated = mdx.frontmatter.updated
  const title = mdx.frontmatter.title
  // const topics = mdx.frontmatter.topics
  const growthStage = mdx.frontmatter.growthStage
  const theme = useTheme()

  return (
    <Layout site={site} frontmatter={mdx.frontmatter}>
      <SEO frontmatter={mdx.frontmatter} isNotePost />
      <Container
        css={css`
          max-width: 940px;
          margin-top: 3em;
          ${bpMaxSM} {
            margin-top: 0.8em;
          }
        `}
      >
        <div
          className="headerBlock"
          css={css`
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            max-width: 840px;
            margin: 0 auto;
        `}>
        <h1
          css={css`
            text-align: left;
            font-size: 3em;
            padding: 0 0 0.4em 0;
          `}
        >
          {title}
        </h1>
        <div
          css={css`
          display: flex;
          flex-wrap: wrap;
          margin-bottom: 1em;
            h6 {
              margin: 0;
              border: 1px solid ${theme.colors.lightestGrey};
              text-align: center;
              align-self: center;
              font-family: ${fonts.regularSans}, 
              sans-serif;
              text-transform: capitalize;
              flex-grow: 1;
              padding: 0.4em 0.8em;
            }
            hr {
              margin: 0;
              background: ${theme.colors.lightestGrey};
              align-self: center;
              border: none;
              flex-grow: 50;
              ${bpMaxSM} {
              display: none;
              }
            }
          `}
        >
          {updated && <h6>Last tended on {updated}</h6>}
          {growthStage && <h6><span role="img" aria-label="a small Seedling"></span> {growthStage}</h6>}

        <hr />
        </div>
        </div>
        <br />
        <MDXRenderer>{mdx.body}</MDXRenderer>
        {/* Next and Previous */}
        <PreviousNext
          prevSlug={prevPage && prevPage.fields.slug}
          prevTitle={prevPage && prevPage.fields.title}
          nextSlug={nextPage && nextPage.fields.slug}
          nextTitle={nextPage && nextPage.fields.title}
        />
        {/* Share Container */}
        <Share
          url={`${config.siteUrl}/${mdx.frontmatter.slug}/`}
          title={title}
          twitterHandle={config.twitterHandle}
        />
      </Container>
      {/* <SubscribeForm /> */}
    </Layout>
  )
}

export const pageQuery = graphql`
  query($id: String!) {
    site {
      ...site
    }
    mdx(fields: { id: { eq: $id } }) {
      frontmatter {
        title
        updated(formatString: "MMMM DD, YYYY")
        slug
        topics
        growthStage
      }
      body
    }
  }
`
4

1 回答 1

0

我不确定是否完全理解您的问题,但对我来说,您似乎没有将您gatsby-node.js的模板链接到Note模板,就像您对其余模板所做的那样。由于在 GraphQL 查询中Note请求不可为空,因此会提示您的问题。id只需将其添加到您的gatsby-node.js

data.notesQuery.edges.forEach(({ node }, i) => {
  // uncomment the following if needed

  //const { edges } = data.notesQuery
  //const prevPage = i === 0 ? null : edges[i - 1].node
  //const nextPage = i === edges.length - 1 ? null : edges[i + 1].node
  //pageRedirects(node)
  createPage({
    path: node.fields.slug,
    component: path.resolve('./src/templates/noteTemplate.js'),
    context: {
      id: node.id,
    },
  })
})
于 2021-04-10T13:57:44.557 回答