带有 Netlify CMSField "thumbnail" 的 Gatsby 图像不能有选择,因为类型 "String" 没有子字段

Gatsby Image with Netlify CMSField "thumbnail" must not have a selection since type "String" has no subfields

从今天开始,我遇到了一个问题,我不知道该如何解决。就 React 和 Gatsby 而言,我有点陌生。发生了什么,目前我正在使用 Netlify CMS 运行的网站上工作。在过去的几天里,一切都很好,但是从今天开始,发生了一些奇怪的事情。我收到以下错误消息:


> hemd-und-fliege-2.1@1.0.0 start
> gatsby develop

success open and validate gatsby-configs, load plugins - 1.221s
success onPreInit - 0.045s
success initialize cache - 0.039s
success copy gatsby files - 0.090s
success Compiling Gatsby Functions - 0.336s
success onPreBootstrap - 0.356s
success createSchemaCustomization - 0.053s

 ERROR #11321  PLUGIN

"gatsby-remark-relative-images" threw an error while running the onCreateNode lifecycle:

No matching file found for src "/images/uploads/bildschirmfoto-2021-07-26-um-11.09.18.png" in static folder "static". Please check static folder name and that file exists at
"static/images/uploads/bildschirmfoto-2021-07-26-um-11.09.18.png". This error will probably cause a "GraphQLDocumentError" later in build. All converted field paths MUST resolve to a matching file in the
 "static" folder.



  Error: No matching file found for src "/images/uploads/bildschirmfoto-2021-07-26-um-11.09.18.png" in static folder "static". Please check static folder name and that file exists at "static/images/uploa
  ds/bildschirmfoto-2021-07-26-um-11.09.18.png". This error will probably cause a "GraphQLDocumentError" later in build. All converted field paths MUST resolve to a matching file in the "static" folder.
  
  - index.js:32 Object.exports.findMatchingFile
    [hemd-und-fliege-2.1]/[gatsby-remark-relative-images]/dist/index.js:32:15
  
  - on-create-node.js:35 Object.<anonymous>
    [hemd-und-fliege-2.1]/[gatsby-remark-relative-images]/dist/on-create-node.js:35:29
  
  - index.js:190 walker
    [hemd-und-fliege-2.1]/[traverse]/index.js:190:22
  
  - index.js:208 
    [hemd-und-fliege-2.1]/[traverse]/index.js:208:29
  
  - Array.forEach
  
  - index.js:298 forEach
    [hemd-und-fliege-2.1]/[traverse]/index.js:298:31
  
  - index.js:203 walker
    [hemd-und-fliege-2.1]/[traverse]/index.js:203:13
  
  - index.js:226 walk
    [hemd-und-fliege-2.1]/[traverse]/index.js:226:7
  
  - index.js:50 Traverse.forEach
    [hemd-und-fliege-2.1]/[traverse]/index.js:50:18
  
  - on-create-node.js:17 Object.exports.onCreateNode
    [hemd-und-fliege-2.1]/[gatsby-remark-relative-images]/dist/on-create-node.js:17:46
  
  - api-runner-node.js:432 runAPI
    [hemd-und-fliege-2.1]/[gatsby]/src/utils/api-runner-node.js:432:22
  
  - api-runner-node.js:588 Promise.catch.decorateEvent.pluginName
    [hemd-und-fliege-2.1]/[gatsby]/src/utils/api-runner-node.js:588:13
  
  - debuggability.js:384 Promise._execute
    [hemd-und-fliege-2.1]/[bluebird]/js/release/debuggability.js:384:9
  
  - promise.js:518 Promise._resolveFromExecutor
    [hemd-und-fliege-2.1]/[bluebird]/js/release/promise.js:518:18
  
  - promise.js:103 new Promise
    [hemd-und-fliege-2.1]/[bluebird]/js/release/promise.js:103:10
  
  - api-runner-node.js:586 
    [hemd-und-fliege-2.1]/[gatsby]/src/utils/api-runner-node.js:586:16
  

success Checking for changed pages - 0.002s
success source and transform nodes - 0.506s
success building schema - 0.914s
success createPages - 0.003s
success createPagesStatefully - 0.191s
info Total nodes: 66, SitePage nodes: 4 (use --verbose for breakdown)
success Checking for changed pages - 0.001s
success update schema - 0.127s
success write out redirect data - 0.005s
success Build manifest and related icons - 0.099s
success onPostBootstrap - 0.107s
info bootstrap finished - 6.002s
success onPreExtractQueries - 0.002s

 ERROR #85922  GRAPHQL

There was an error in your GraphQL query:

      Field "thumbnail" must not have a selection since type "String" has no subfields.

      This can happen if you e.g. accidentally added { } to the field "thumbnail". If you didn't expect "thumbnail" to be of type "String" make sure that your input source and/or plugin is correct.
      However, if you expect "value" to exist, the field might be accessible in another subfield. Please try your query in GraphiQL and use the GraphiQL explorer to see which fields you can query and
what shape they have.

      It is recommended to explicitly type your GraphQL schema if you want to use optional fields. This way you don't have to add the mentioned
      "dummy content". Visit our docs to learn how you can define the schema for "undefined":
      https://www.gatsbyjs.com/docs/reference/graphql-data-layer/schema-customization#creating-type-definitions

File: src/pages/index.js:30:23

failed extract queries from components - 2.116s
success write out requires - 0.006s
success run page queries - 0.020s - 2/2 99.18/s
success Caching HTML renderer compilation - 0.002s
⠸ Building development bundle
 DONE  Compiled successfully in 6990ms                                                                                                                                                             18:09:15
⠀
 I  Netlify CMS is running at http://localhost:8000/admin/
⠀
You can now view hemd-und-fliege-2.1 in the browser.
⠀
  http://localhost:8000/
⠀
View GraphiQL, an in-browser IDE, to explore your site's data and schema
⠀
  http://localhost:8000/___graphql
⠀
Note that the development build is not optimized.
To create a production build, use gatsby build
⠀
warn 
/Users/mw/PROJECTS/hemd-und-fliege-2.1/src/components/BlogEntry/index.js
  1:27  warning  'useRef' is defined but never used     no-unused-vars
  1:35  warning  'useEffect' is defined but never used  no-unused-vars

/Users/mw/PROJECTS/hemd-und-fliege-2.1/src/components/Headline/index.js
  73:6  warning  React Hook useEffect has a missing dependency: 'gsap'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

✖ 3 problems (0 errors, 3 warnings)

success Building development bundle - 10.477s
success Writing page-data.json files to public directory - 0.157s - 2/4 25.45/s

我认为它与 gatsby-remark-relative-images 插件有关,但我不明白,为什么它前几天有效,而今天却无效。同样奇怪的是,当我尝试以编程方式创建页面并为此制作了一个 gatsby-node.js 文件时,它就开始了。删除该文件后,错误消息继续。我在这里和那里尝试了一些关于我的 config.yml 文件的东西,它再次起作用了。我再次尝试创建 gatsby-node.js 文件,但问题又回来了。我真的不知道发生了什么。

以下是一些附加文件:

gatsby-config

module.exports = {
  siteMetadata: {
    siteUrl: "https://www.yourdomain.tld",
    title: "hemd-und-fliege-2.1",
  },
  plugins: [
    "gatsby-plugin-netlify-cms",
    "gatsby-plugin-styled-components",
    "gatsby-plugin-image",
    {
      resolve: "gatsby-plugin-google-analytics",
      options: {
        trackingId: "TEST",
      },
    },
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-sitemap",
    {
      resolve: "gatsby-plugin-manifest",
      options: {
        icon: "src/images/icon.png",
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: `${__dirname}/src/images/`,
      },
      __key: "images",
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "pages",
        path: `${__dirname}/src/pages/`,
      },
      __key: "pages",
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "markdown-pages",
        path: `${__dirname}/_posts/werke`,
      },
      __key: "markdown-pages",
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "uploaded-images",
        path: `${__dirname}/static/images`,
      },
      __key: "uploaded-images",
    },
    "gatsby-transformer-remark",
    "gatsby-plugin-sharp",
    "gatsby-transformer-sharp",
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          `gatsby-remark-relative-images`,
          {
            resolve: `gatsby-remark-images`,
            options: {},
          },
        ],
      },
    },
  ],
};

gatsby-node

const path = require(`path`);
const { createFilePath } = require(`gatsby-source-filesystem`);

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

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode });
    createNodeField({
      name: `slug`,
      node,
      value,
    });
  }
};

const buildPages = (edges, createPage) => {
  const pages = edges.filter((edge) => {
    if ("templateKey" in edge.node.frontmatter) {
      return edge;
    }
  });

  // create pages with the filtered edges
  pages.map((page) => {
    console.log(`Creating page ${JSON.stringify(page.node.frontmatter)}`);

    createPage({
      path: page.node.fields.slug,
      // getting the component to render the page using the templateKey property
      component: path.resolve(
        `src/templates/${String(page.node.frontmatter.templateKey)}.js`
      ),
      context: {
        id: page.node.id,
        slug: page.node.fields.slug,
      },
    });
  });
};

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

  // graphql query for pages only
  const result = await graphql(
    `
      {
        allMarkdownRemark(
          limit: 1000
          filter: { fileAbsolutePath: { regex: "/(work-post)/i" } }
        ) {
          edges {
            node {
              id
              fields {
                slug
              }
              frontmatter {
                title
                templateKey
              }
            }
          }
        }
      }
    `
  );
  // if errors then throw
  if (result.errors) {
    throw result.errors;
  }
  console.log("Creating pages ---->>>>");
  // Create pages
  buildPages(result.data.allMarkdownRemark.edges, createPage);
};

index.js

import * as React from "react";
import { graphql } from "gatsby";
import gsap from "gsap";
import { Layout } from "../components/layout";

// Components
import { Head } from "../components/Headline";
import { BlogEntry } from "../components/BlogEntry";

// markup
const IndexPage = ({ data }) => {
  const edges = data.allMarkdownRemark.edges;

  return (
    <Layout>
      <Head gsap={gsap} />
      <BlogEntry edges={edges} />
    </Layout>
  );
};

export const query = graphql`
  query {
    allMarkdownRemark {
      edges {
        node {
          id
          frontmatter {
            title
            thumbnail {
              childImageSharp {
                gatsbyImageData(layout: FULL_WIDTH)
              }
            }
          }
        }
      }
    }
  }
`;

export default IndexPage;

这是我的存储库和当前分支的link:

https://github.com/M-WRI/hemd-und-fliege-2.0/tree/moritz-dev

我知道我的描述可能有些地方不够扎实,但我希望有人能帮助我。非常感谢。

这个问题可以有多种解决方案,具体取决于引起它的原因。通常,通常发生的情况是 Gatsby 无法创建 thumbnail 节点,因为它有一个不相关的类型(字符串),它应该是一个图像节点,因为父子节点之间的相关性以某种方式丢失了。

可能的解决方案:

  • 运行 gatsby clean:清理缓存。然后,gatsby develop 再次项目。

  • 检查 config.yml 中的 media_folderpublic_folder:在你的情况下,对我来说,它们看起来都不错。

  • 使用 gatsby-remark-relative-images-v2 插件:Netlify CMS 不完全支持相对路径(目前),所以与此同时,您可能需要该插件的帮助。这是因为图像在节点文件夹之外。

    安装后。只需将其添加为

    的选项即可
    {
        resolve: `gatsby-transformer-remark`,
        options: {
          plugins: [
            {
              resolve: `gatsby-remark-relative-images-v2`,
            },
            {
              resolve: `gatsby-remark-images`,
              options: {},
            },
          ],
        },
      },
    

    之后,您需要在 gatsby-node.js 中包含以下代码段:

    const { fmImagesToRelative } = require('gatsby-remark-relative-images-v2');
    
    exports.onCreateNode = ({ node }) => {
       fmImagesToRelative(node);
    };
    

    在您的情况下,您使用的是我建议的同一插件的 v1,但您缺少 gatsby-node.js 文件中的先前配置。上次我遇到你的问题时,v2 救了我,但如果你愿意,你可能想尝试一下 v1 + 代码段。

    记得在每次试用时清理缓存。

此外,尝试为 foreach 更改 map 循环,因为您想在 pages 的每个实例中应用 createPage API。

我也有这个问题,this github issue帮我解决了。 gatsby-remark-images(v1 和 v2)一直给我错误,但通过多次试验我发现你可以明确设置字段类型。这将公开所有必需的节点,您可以访问 gatsbyImageData。

这是我添加到gatsby的代码-node.js

exports.createSchemaCustomization = ({ actions }) => {
    const { createTypes } = actions
  
    createTypes(`
        type MarkdownRemark implements Node {
            frontmatter: Frontmatter
        }
        type Frontmatter {
            thumbnail: File @fileByRelativePath
        }
    `)
}