代码之家  ›  专栏  ›  技术社区  ›  Andrew Ingram

使用Gatsby将图像附加到节点的标准方法是什么?

  •  -1
  • Andrew Ingram  · 技术社区  · 7 年前

    我现在 onCreateNode gatsby-node.js 在创建某些节点后修改它们。我想做的一件事是将图像(或者其他类型的文件)附加到节点。假设映像存在于文件系统的其他地方,我可以通过调用一个名为 getImageForNode(node) ,如何将其附加到节点,以便:

    1. /static/ 在建设期间,以便它可以由网站服务。

    gatsby-source-filesystem createRemoteFileNode 函数,但它只适用于通过internet提供服务的图像(我不想为此设置一个本地http服务器,而且它似乎不支持 file://

    0 回复  |  直到 7 年前
        1
  •  2
  •   Derek Nguyen    7 年前

    Gatsby附带了一些插件可以帮助您:

    gatsby-source-filesystem 会把文件数据放到你的盖茨比应用程序中, gatsby-transformer-sharp 会问的 gatsby-plugin-sharp

    您可以请求gatsby将一个文件链接到另一个节点,方法是在该节点中添加一个相对路径作为字段。你也可以手动链接。

    设置

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: absolute/path/to/a/directory,
        name: `anything`,
      },
    },
    

    它也可以找到根目录之外的目录。

    path: path.resolve(__dirname, '../../images')
    

    将现有路径添加到相对节点

    假设你有一个 Json 节点,创建者 gatsby-transformer-remark

        const fileAbsolutePath = /* find this node's absolute path */
        const imageAboslutePath = /* do your get absolute path thing */
        const imageRelativePath = path.relative(fileAbsolutePath, imageAboslutePath)
    
        createNodeField({
          node,
          name: `image`,
          value: imageRelativePath,
        })
    

    这将链接新字段 image 到文件节点,在其中可以找到 imageSharp 包含图像信息的节点。

    然后你可以像

    query {
      markdownRemark {
        fields {               <-- fields created by `createNodeField` will live here
          image {              <-- point to a file node
            childImageSharp {  <-- point to imageSharp node of this file
              fixed {
                width          <-- see more info in gatsby-plugin-sharp documentation
                height
                srcSet
                src
              }
            }
          }
        }
      }
    }
    

    如果要修改的节点没有文件,则必须手动链接它。 createNodeField

        createNodeField({
          node,
          name: 'target___NODE', <--- `___NODE` will resolve to another node
          value: targetNode.id,
        })
    

    other answer of mine .

    推荐文章