在创建 DigitalGarden 笔记页面期间的 GraphQL 查询投诉

如何解决在创建 DigitalGarden 笔记页面期间的 GraphQL 查询投诉

我正在尝试通过了解 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.js中,createPages首先查询frontmatter和note的内容,并根据特定模板(在templates文件夹中找到)生成页面。

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

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

在运行 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 工作正常,但永远不会生成注释页面。

notesQuery 中的 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" },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" },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" },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'),})
    })

    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'),})
    })

    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'),})
    })
  })
}

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',value: node.frontmatter.published,})

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

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

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

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

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

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

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

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

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

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

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

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

    createNodeField({
      name: 'growthStage',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
    }
  }
`

解决方法

我不确定是否完全理解您的问题,但在我看来,您似乎没有像处理其他模板那样将 Note 链接到 Note 模板。由于 id 在 GraphQL 查询中请求不可为空的 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,},}) }) 中:

{{1}}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res