首先,您需要允许 Gatsby 通过设置文件系统从这些图像创建可查询节点:
const path = require(`path`)
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: path.join(__dirname, `src`, `images`),
},
},
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
],
}
在构建时,Gatsby 将识别 /src/images 文件夹,并在使用变换器和锐器处理您的图像后创建 GraphQL 节点。
您将公开一些有关文件系统配置的有用过滤器和节点,在 localhost:8000/___graphql 中对其进行测试,但它们应该如下所示:
{
allFile(filter: { sourceInstanceName: { eq: "images" } }) {
edges {
node {
childImageSharp {
gatsbyImageData(
width: 200
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
)
}
}
}
}
}
sourceInstanceName images 代表gatsby-source-filesystem 中的name 属性。
您的图像数据由props.data.allFile.node 保存,因此您可以在任何页面中:
import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
function YourPage({ data }) {
return (
<section>
{data.allFile.edges.map(({ node }) => <GatsbyImage image={node.childImageSharp.gatsbyImageData})} alt={node.title} key={node.title}/>
</section>
)
}
export const pageQuery = graphql`
query {
allFile(filter: { sourceInstanceName: { eq: "images" } }) {
edges {
node {
title
childImageSharp {
gatsbyImageData(
width: 200
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
)
}
}
}
}
}
`
根据您的要求或规范对其进行调整。