发布于 2026-01-06 4 阅读
0

Gatsby Image 和 Gatsby.js V2 使用入门

Gatsby Image 和 Gatsby.js V2 使用入门

本文最初发布于codebushi.com。
如需观看视频教程,请访问https://www.youtube.com/watch?v=kOrohVsq_kI

盖茨比图像

Gatsby.js V2最近发布了, Gatsby Image 的实现方式也进行了一些细微的改动。Gatsby Image 是一个 React 组件,可以轻松优化网站上的所有图片。它会自动调整图片大小,避免在移动设备上加载过大的图片,并且还会使用炫酷的“模糊”效果进行图片懒加载,从而显著提升页面初始加载速度。如果您是 Gatsby 新手,我强烈建议您先阅读官方教程,熟悉 Gatsby 的工作原理。

将 Gatsby 图片添加到静态网站可能有点棘手,尤其因为 Gatsby 使用 GraphQL 来查询和加载图片,然后才能使用它们。以下是所需步骤的详细说明:

1)安装所需的 npm 包并配置您的gatsby-config.js设置。

2) 测试是否可以使用 GraphQL 查询图像。

3) 选择您需要的图像类型(固定或流动),并将查询添加到您的页面。

<Img>4)在页面上使用 Gatsby Image标签。

以下是最终产品的演示:

Gatsby图像演示 查看源代码

安装和配置 Gatsby 镜像

我们首先来安装默认的 Gatsby Starter。您可以克隆仓库或使用 Gatsby CLI 来安装 Starter。

gatsby new image-demo https://github.com/gatsbyjs/gatsby-starter-default
cd image-demo/
Enter fullscreen mode Exit fullscreen mode

如果您使用了命令行界面 (CLI),则需要继续使用 `yarn install`,yarn因为初始软件包是通过 `yarn install` 安装的yarn,并且会生成一个 `yarn.lock` 文件。如果您克隆了仓库并使用了 `yarn install` npm install,则需要继续使用npm`yarn install`,以免混用不同的软件包安装程序。yarn在本演示的剩余部分,我将使用 `yarn install`。

安装 Gatsby 镜像

yarn add gatsby-image
Enter fullscreen mode Exit fullscreen mode

我们还需要另外三个软件包:gatsby-transformer-sharpgatsby-plugin-sharpgatsby-source-filesystem。如果您未使用默认的 starter 版本,并且已经安装了这些软件包,则可以跳过此步骤。

yarn add gatsby-transformer-sharp gatsby-plugin-sharp gatsby-source-filesystem
Enter fullscreen mode Exit fullscreen mode

gatsby-source-filesystem软件包允许 Gatsby 对特定目录中的图像使用 GraphQL 并执行查询。这两个sharp插件负责在显示图像之前对其进行处理。

打开你的gatsby-config.js配置文件,并将插件添加到其中。我会将它们添加到现有插件之前。你的文件应该如下所示:

module.exports = {
  siteMetadata: {
    title: 'Gatsby Default Starter',
  },
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/images`,
        name: 'images',
      },
    },
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
    'gatsby-plugin-react-helmet',
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: 'gatsby-starter-default',
        short_name: 'starter',
        start_url: '/',
        background_color: '#663399',
        theme_color: '#663399',
        display: 'minimal-ui',
        icon: 'src/images/gatsby-icon.png', // This path is relative to the root of the site.
      },
    },
    'gatsby-plugin-offline',
  ],
}

Enter fullscreen mode Exit fullscreen mode

重要提示:请务必指定正确的path图片文件夹!程序gatsby-source-filesystem会在这个文件夹中查找图片。由于我们使用的是默认的初始模板,所以已经存在一个文件夹,我们将使用该文件夹。请从Unsplash/src/images下载一些图片并添加到该文件夹​​中。

使用 GraphQL 测试图像查询

安装好插件后,我们就可以在开发模式下启动我们的网站了。

gatsby develop
Enter fullscreen mode Exit fullscreen mode

导航至此http://localhost:8000/处以查看网站的开发模式。现在我们将使用 GraphiQL 界面来了解图像查询的工作原理。前往此处http://localhost:8000/___graphql以查看网站的 GraphiQL 视图。在这里,我们可以测试不同的查询。我已将 3 张图片添加到我的/src/images文件夹中,并分别命名为one.jpg two.jpgthree.jpg。要查询 ,one.jpg我将使用以下代码:

query {
  imageOne: file(relativePath: {eq: "one.jpg"}) {
    childImageSharp {
      fluid(maxWidth: 1000) {
        base64
        tracedSVG
        aspectRatio
        src
        srcSet
        srcWebp
        srcSetWebp
        sizes
        originalImg
        originalName
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

点击播放按钮后,您应该会在响应列中看到数据。这证明 Gatsby 能够找到您的图像并进行处理。

尝试切换file(relativePath: {eq: "one.jpg"})到该文件夹​​中的其他图像,并确保可以看到数据返回。

添加 GraphQL 查询

现在我们可以复制这个查询语句,并在首页组件中使用它。打开 `<head>` 文件src/pages/index.js。你需要graphql从 `<head>`'gatsby'和 ` Img<head>`导入 `<head> 'gatsby-image'` 模块。我们将把查询语句添加到页面中,最终效果如下:

import React from 'react'
import { Link, graphql } from 'gatsby'
import Img from 'gatsby-image'

import Layout from '../components/layout'

const IndexPage = (props) => (
  <Layout>
    <h1>Hi people</h1>
    <p>Welcome to your new Gatsby site.</p>
    <p>Now go build something great.</p>
    <Link to="/page-2/">Go to page 2</Link>
  </Layout>
)

export default IndexPage

export const pageQuery = graphql`
  query {
    imageOne: file(relativePath: { eq: "one.jpg" }) {
      childImageSharp {
        fluid(maxWidth: 1000) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
`
Enter fullscreen mode Exit fullscreen mode

查询语句与之前略有不同,我们移除了所有内部字段fluid(maxWidth: 1000) {},并使用了...GatsbyImageSharpFluid`<query_fragment>`,这是一个“查询片段”。由于一些限制,我们之前无法在 GraphiQL 中使用 `<query_fragment>` ,但现在可以了。您可以在Gatsby Image 的 README 文件...GatsbyImageSharpFluid中了解更多关于不同片段的信息

重要提示:请注意,这file(relativePath: { eq: "one.jpg" })部分内容保持不变,这是因为该部分relativePath并非相对于当前目录,而是相对于您之前在`.`index.js中指定的文件夹。无需更改 `.` 的任何内容gatsby-config.jsgatsby-source-filesystemrelativePath

Gatsby Image 提供了两种响应式图片类型:`images`fixedfluid`images`。这两种类型的区别会影响你的查询结果。`images` 查询fixed具有固定的宽度和高度,用于支持不同的屏幕分辨率。`images`fluid查询具有最大宽度(有时还有最大高度),会创建多个图片以支持不同的屏幕尺寸。大多数情况下,我使用 `images`fluid类型,因为我的图片会根据屏幕尺寸而变化。如果你想使用 `images` 类型fixed或想了解更多关于这两种类型的信息,请查看Readme 文件

使用 Gatsby 图像组件

页面上已经有了查询语句,可以通过组件访问 GraphQL 数据propsIndexPage数据的完整路径是 `<data_path>` props.data.imageOne.childImageSharp.fluid。我们可以<Img>像这样将其传递给组件:

<Img fluid={props.data.imageOne.childImageSharp.fluid} />
Enter fullscreen mode Exit fullscreen mode

你可以随意解构这段代码,为了清晰起见,我使用了完整路径。图片现在应该会显示在你的开发网站上了!要获取全部三张图片,只需复制粘贴imageOne代码块,并分别重命名为 `<image_name>`、`<image_name>`imageTwo和 ` <image_name> imageThree`。你可以随意命名这些代码块,只需确保它与你传递给组件的名称一致即可<Img />

query {
  imageOne: file(relativePath: { eq: "one.jpg" }) {
    childImageSharp {
      fluid(maxWidth: 1000) {
        ...GatsbyImageSharpFluid
      }
    }
  }
  imageTwo: file(relativePath: { eq: "two.jpg" }) {
    childImageSharp {
      fluid(maxWidth: 1000) {
        ...GatsbyImageSharpFluid
      }
    }
  }
  imageThree: file(relativePath: { eq: "three.jpg" }) {
    childImageSharp {
      fluid(maxWidth: 1000) {
        ...GatsbyImageSharpFluid
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

各个组件看起来会是这样:

<Img fluid={props.data.imageOne.childImageSharp.fluid} />
<Img fluid={props.data.imageTwo.childImageSharp.fluid} />
<Img fluid={props.data.imageThree.childImageSharp.fluid} />
Enter fullscreen mode Exit fullscreen mode

该查询中重复了很多相同的内容,可以通过创建自定义片段来简化。提取这些childImageSharp代码块并创建一个新的片段,如下所示:

export const fluidImage = graphql`
fragment fluidImage on File {
  childImageSharp {
    fluid(maxWidth: 1000) {
      ...GatsbyImageSharpFluid
    }
  }
}
`;
Enter fullscreen mode Exit fullscreen mode

然后我们可以用这段新代码片段替换重复的代码,如下所示:

export const pageQuery = graphql`
  query {
    imageOne: file(relativePath: { eq: "one.jpg" }) {
      ...fluidImage
    }
    imageTwo: file(relativePath: { eq: "two.jpg" }) {
      ...fluidImage
    }
    imageThree: file(relativePath: { eq: "three.jpg" }) {
      ...fluidImage
    }
  }
`
Enter fullscreen mode Exit fullscreen mode

现在我们的首页上会显示全部三张图片!您可以尝试不同的 Gatsby 片段来实现不同的加载效果。例如,`<img src="my-page" />`...GatsbyImageSharpFluid会产生“模糊向上”的效果,您可以尝试...GatsbyImageSharpFluid_tracedSVG其他效果,也可以尝试使用固定图片进行实验。

Gatsby图像演示 查看源代码

文章来源:https://dev.to/changoman/an-introduction-to-using-gatsby-image--gatsbyjs-v2-2lbg