@aaaz/gatsby-plugin-remote-images 中文文档教程

发布于 4年前 浏览 18 项目主页 更新于 3年前

gatsby-plugin-remote-images

从另一个节点上的任何字符串字段下载图像,以便这些图像可以 使用 gatsby-image 查询。

Usage

Install

首先,安装插件。

npm install --save gatsby-plugin-remote-images

其次,使用插件设置 gatsby-config.js。 最常见的配置 会是这样的:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-remote-images`,
      options: {
        nodeType: 'MyNodes',
        imagePath: 'path.to.image',
      },
    },
  ],
};

Options

Option NameDescriptionRequiredDefault
nodeTypeThe node type that has the images you want to grab. This is generally the camelcased version of the word after the 'all' in GraphQL ie. allMyImages type is myImagesnull
imagePathFor simple object traversal, this is the string path to the image you want to use, relative to the node. This uses lodash .get, see docs for accepted formats here. For traversing objects with arrays at given depths, see how to handle arrays along the path below.null
nameName you want to give new image field on the node. Defaults to localImage.localImage
authAdds htaccess authentication to the download request if passed in.{}
extSets the file extension. Useful for APIs that separate the image file path from its extension. Or for changing the extension. Defaults to existing file extension.null
prepareUrlAllows modification of the URL per image if needed. Expects a function taking the original URL as a parameter and returning the desired URL.null
typeTell the plugin that the leaf node is an array of images instead of one single string. Only option here is array. For example usage, see here.object

Example Config with Optional Options

但是,您可能需要更多可选配置,记录在此处。

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-remote-images`,
      options: {
        nodeType: 'MyNodes',
        imagePath: 'path.to.image',
        // ** ALL OPTIONAL BELOW HERE: **
        name: 'theNewImageField',
        auth: { htaccess_user: `USER`, htaccess_pass: `PASSWORD` },
        ext: '.jpg',
        prepareUrl: url => (url.startsWith('//') ? `https:${url}` : url),
      },
    },
  ],
};

Why?

为什么需要这个插件? 神奇的 gatsby-image 工具只适用于 本地存储图像的相对 路径。 这使您可以在来自的图像上使用它 具有绝对 路径的 API。 例如,看看来自一个的这两个响应 GraphQL 查询:

查询

allMyNodes {
    edges {
      node {
        id
        imageUrl
      }
    }
  }

绝对 imageUrl 不可用于 gatsby-image

allMyNodes: [
  {
    node: {
      id: 123,
      imageUrl: 'http://remoteimage.com/url.jpg',
    },
  },
];

相对 imageUrl 可用于 gatsby-image

allMyNodes: [
  {
    node: {
      id: 123,
      imageUrl: 'localImages/url.jpg',
    },
  },
];

如果您不控制 API您正在点击(许多第三方 API 返回 带有字符串的字段到图像的绝对路径),这意味着那些图像 没有通过 gatsby-image 运行,您将失去所有好处。

要获取图像并使它们可用于上述示例,请遵循 安装说明和您的配置应该如下所示:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-remote-images`,
      options: {
        nodeType: 'MyNodes',
        imagePath: 'imageUrl',
        // OPTIONAL: Name you want to give new image field on the node.
        // Defaults to 'localImage'.
        name: 'allItemImages',
      },
    },
  ],
};

现在,如果我们查询 allMyNodes,我们可以像查询任何 gatsby-image 节点一样查询:

allMyNodes {
  edges {
    node {
      localImage {
        childImageSharp {
          fluid(maxWidth: 400, maxHeight: 250) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
}

注意: 许多 Gatsby 源插件已经这样做了这个为你工作 兜帽。 因此,如果您使用的是普通 CMS 的 Gatsby 插件,那么很有可能 你不需要这个!

Common Issues

gatsby-source-graphql

由于 gatsby-source-graphql 创建节点的方式,目前不可能 任何转换器类型的插件都可以遍历该插件的数据。 请阅读本期的解释。 一旦在 gatsby-source-graphql 中修复,这个插件将被测试 以确保它也适用于它。

Traversing objects with arrays

由于某些 GraphQL API 会发回带有嵌套数组的对象 目标数据存活,gatsby-plugin-remote-images也支持遍历 具有任意深度数组的对象。 要选择加入此功能,请添加 数组字面量,[],到你要表示的节点的末尾是一个数组。

给定这样的对象结构:

allMyNodes {
  nodes: [
    {
      imageUrl: 'https://...'
    },
    ...
  ]
}

要获取图像并使它们可用于上面的示例,您的配置 应该看起来像这样:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-remote-images`,
      options: {
        nodeType: 'MyNodes',
        imagePath: 'nodes[].imageUrl',
      },
    },
  ],
};

现在,如果我们查询 allMyNodes,我们可以像查询任何 gatsby-image 节点一样查询:

allMyNodes {
  nodes {
    localImage {
      childImageSharp {
        fluid(maxWidth: 400, maxHeight: 250) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
}

注意:lodash .get本身不支持这种语法,它仍然是 用于遍历对象结构,所以 .get 的文档仍然 完全适用。

Handling an Array of Image URLs

如果您的 API 提供了图像数组的图像路径,而不仅仅是 第一,有一种方法可以用插件来处理这个问题。 例如有 沿着图像路径某处的数组, 见上文

例如,您的 API 返回:

// MyNode
{
  date: '1-1-2010',
  category: 'cats'
  // Note that here there are multiple images at the *leaf* node where the images are found.
  images: [
    'https://.../image1.png',
    'https://.../image2.png'
  ]
}

要使您的本地图像字段成为这些图像的数组,请调整您的配置 因此:

 {
   resolve: `gatsby-plugin-remote-images`,
   options: {
     nodeType: 'MyNodes',
     // Making this plural (optional).
     name: 'localImages',
     // Path to the leaf node.
     imagePath: 'images',
     // Set type to array.
     type: 'array'
   }
}

现在,如果我们查询 allMyNodes,我们可以像查询任何 gatsby-image 节点一样查询, 但是现在 localImage(或上面示例中的 localImages)我们会得到一个 一组 Gatsby 图像,而不是只有一个。

allMyNodes {
  nodes {
    localImages {
      childImageSharp {
        fluid(maxWidth: 400, maxHeight: 250) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
}

???? gatsby-plugin-remote-images

Download images from any string field on another node so that those images can be queried with gatsby-image.

Usage

Install

First, install the plugin.

npm install --save gatsby-plugin-remote-images

Second, set up the gatsby-config.js with the plugin. The most common config would be this:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-remote-images`,
      options: {
        nodeType: 'MyNodes',
        imagePath: 'path.to.image',
      },
    },
  ],
};

Options

Option NameDescriptionRequiredDefault
nodeTypeThe node type that has the images you want to grab. This is generally the camelcased version of the word after the 'all' in GraphQL ie. allMyImages type is myImagesnull
imagePathFor simple object traversal, this is the string path to the image you want to use, relative to the node. This uses lodash .get, see docs for accepted formats here. For traversing objects with arrays at given depths, see how to handle arrays along the path below.null
nameName you want to give new image field on the node. Defaults to localImage.localImage
authAdds htaccess authentication to the download request if passed in.{}
extSets the file extension. Useful for APIs that separate the image file path from its extension. Or for changing the extension. Defaults to existing file extension.null
prepareUrlAllows modification of the URL per image if needed. Expects a function taking the original URL as a parameter and returning the desired URL.null
typeTell the plugin that the leaf node is an array of images instead of one single string. Only option here is array. For example usage, see here.object

Example Config with Optional Options

However, you may need more optional config, which is documented here.

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-remote-images`,
      options: {
        nodeType: 'MyNodes',
        imagePath: 'path.to.image',
        // ** ALL OPTIONAL BELOW HERE: **
        name: 'theNewImageField',
        auth: { htaccess_user: `USER`, htaccess_pass: `PASSWORD` },
        ext: '.jpg',
        prepareUrl: url => (url.startsWith('//') ? `https:${url}` : url),
      },
    },
  ],
};

Why?

Why do you need this plugin? The fantastic gatsby-image tool only works on relative paths to locally stored images. This lets you use it on images from an API with an absolute path. For example, look at these two response from one GraphQL query:

Query

allMyNodes {
    edges {
      node {
        id
        imageUrl
      }
    }
  }

Absolute imageUrl NOT available to gatsby-image

allMyNodes: [
  {
    node: {
      id: 123,
      imageUrl: 'http://remoteimage.com/url.jpg',
    },
  },
];

Relative imageUrl IS available to gatsby-image

allMyNodes: [
  {
    node: {
      id: 123,
      imageUrl: 'localImages/url.jpg',
    },
  },
];

If you don't control the API that you are hitting (many third party APIs return a field with a string to an absolute path for an image), this means those image aren't run through gatsby-image and you lose all of the benefits.

To get the images and make them available for the above example, follow the install instructions and your config should look like this:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-remote-images`,
      options: {
        nodeType: 'MyNodes',
        imagePath: 'imageUrl',
        // OPTIONAL: Name you want to give new image field on the node.
        // Defaults to 'localImage'.
        name: 'allItemImages',
      },
    },
  ],
};

Now, if we query allMyNodes we can query as we would any gatsby-image node:

allMyNodes {
  edges {
    node {
      localImage {
        childImageSharp {
          fluid(maxWidth: 400, maxHeight: 250) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
}

Note: Many Gatsby source plugins already do this work for you under the hood. So if you are working with a common CMS's Gatsby plugin, odds are that you don't need this!

Common Issues

gatsby-source-graphql

Due to the way gatsby-source-graphql creates nodes, it is currently impossible for any transformer type plugin to traverse the data from that plugin. Please read this issue for explanation. As soon as that as fixed in gatsby-source-graphql, this plugin will be tested to make sure it works with it as well.

Traversing objects with arrays

Since some GraphQL APIs will send back objects with nested arrays where your target data lives, gatsby-plugin-remote-images also supports traversing objects that have arrays at arbitrary depths. To opt in to this feature, add an array literal, [], to the end of the node you want to indicate is an array.

Given an object structure like this:

allMyNodes {
  nodes: [
    {
      imageUrl: 'https://...'
    },
    ...
  ]
}

To get the images and make them available for the above example, your config should look like this:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-remote-images`,
      options: {
        nodeType: 'MyNodes',
        imagePath: 'nodes[].imageUrl',
      },
    },
  ],
};

Now, if we query allMyNodes we can query as we would any gatsby-image node:

allMyNodes {
  nodes {
    localImage {
      childImageSharp {
        fluid(maxWidth: 400, maxHeight: 250) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
}

Note: While lodash .get doesn't natively support this syntax, it is still used to traverse the object structure, so the documentation for .get still applies in full.

Handling an Array of Image URLs

In case your API offers an image path to an array of images, instead of just one, there is a way to handle that with the plugin. For instances where there is an array somewhere along the path to the images, see above.

For example, you API returns:

// MyNode
{
  date: '1-1-2010',
  category: 'cats'
  // Note that here there are multiple images at the *leaf* node where the images are found.
  images: [
    'https://.../image1.png',
    'https://.../image2.png'
  ]
}

To make your local image field an array of these images, adjust your config accordingly:

 {
   resolve: `gatsby-plugin-remote-images`,
   options: {
     nodeType: 'MyNodes',
     // Making this plural (optional).
     name: 'localImages',
     // Path to the leaf node.
     imagePath: 'images',
     // Set type to array.
     type: 'array'
   }
}

Now, if we query allMyNodes we can query as we would any gatsby-image node, but now localImage (or localImages as in the example above) we would get an array of Gatsby images, instead of just one.

allMyNodes {
  nodes {
    localImages {
      childImageSharp {
        fluid(maxWidth: 400, maxHeight: 250) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
}
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文