如何在gatsby源插件上加载本地图像? [英] How to load a local image on a gatsby source plugin?

查看:72
本文介绍了如何在gatsby源插件上加载本地图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json文件和一个包含图片的文件夹

I have a json file and a folder with images

plugins/
└── gatsby-source-cars/
    ├── images/
    ├── cars.json
    └── gatsby-node.js

文件 cars.json 包含一个数组,每个索引都是一个对象,该对象包含具有图像相对路径的键

the file cars.json contains an array and each index is an object that contains a key with the relative path to the image

我想将图像文件加载到sourceNodes上,而仅将其与 gatsby-image 插件一起使用的路径

I want to load the image file on sourceNodes instead just the path to use with gatsby-image plugin

推荐答案

我假设您要使用Sharp图像处理本地图像,因为您说过要与 gatsby-image 一起使用,因此表示您已安装 gatsby-plugin-sharp gatsby-transformer-sharp .

I assume that you want to process your local images with sharp since you said you want to use it with gatsby-image, this means you have gatsby-plugin-sharp and gatsby-transformer-sharp installed.

通常,必须使用 gatsby-source-filesystem 将图像加载为文件"节点.但是 gatsby-transformer-sharp 仅检查节点是否具有扩展名"字段,并且-如果它是有效文件类型之一,则对其进行处理.我们可以通过将其字段赋予 extension &来欺骗"它,使其认为我们的节点是File节点. absolutePath .

Usually gatsby-source-filesystem is necessary to load the image as File node. But gatsby-transformer-sharp only checks if a node has the field 'extension' and -- if it is one of the valid file types -- processes it. We can 'trick' it into thinking our node is a File node, by giving it the fields extension & absolutePath.

给出以下结构:

plugins/
└── gatsby-source-my-plugin/
    ├── images/
    |     └──image01.png
    ├── images.json  //  [{ "01": "./images/image01.png" }]
    └── gatsby-node.js

gatsby-node.js 可能看起来像这样:

const path = require('path')
const fs = require('fs-extra')

exports.sourceNodes = async ({ actions, createNodeId, createContentDigest }) => {
  const { createNode } = actions

  const imageList = await fs.readJson(path.resolve(__dirname, './images.json'))
  imageList.forEach(img => {

    const [ id, imgPath ] = Object.entries(img)[0]
    const { name, ext } = path.parse(imgPath) // get file name & extension
    const absolutePath = path.resolve(__dirname, imgPath)
    const data = {
      name,
      ext,
      absolutePath,                  // <-- required
      extension: ext.substring(1),   // <-- required, remove the dot in `ext`
    }
    const imageNode = {
      ...data,
      id: createNodeId(`my-plugin-image-${id}`),
      children: [],
      internal: {
        type: 'MyPluginNode',
        contentDigest: createContentDigest(data)
      }
    }

    createNode(imageNode)
  })
}

稍后,您可以查询图像:

Later, you can query the images:

{
  allMyPluginNode {
    nodes {
      childImageSharp {
        fixed(width:200) {
          src
        }
      }
    }
  }
}

这篇关于如何在gatsby源插件上加载本地图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆