gatsby_使用gatsby-image和gatsby-plugin-sharp的Gatsby中的图像

gatsby

Ensuring that users get the best experience with images on the web can be a tedious task. However, with Gatsby, we can leverage the power of Sharp to get the best performance with a little setup and a rich toolset.

确保用户获得最佳的网络图像体验可能是一项繁琐的任务。 但是,借助Gatsby,我们可以通过少量的设置和丰富的工具集来利用Sharp的强大功能来获得最佳性能。

In this article, we’ll take a look at the gatsby-image component and how it can simplify the process of using images in various scenarios. The steps in this guide assume you have a working Gatsby project. So if you haven’t already, you can get started with Gatsby by following along the Gatsby First Steps article.

在本文中,我们将研究gatsby-image组件以及它如何简化在各种情况下使用图像的过程。 本指南中的步骤假定您有一个正常的Gatsby项目。 因此,如果您还没有开始,请按照《 盖茨比第一步》一文开始使用盖茨

入门 (Getting Started)

Let’s get started by installing the necessary plugins. Depending on the Gatsby starter you’re using, these might already be installed. Check the package.json to see if that’s the case.

让我们从安装必要的插件开始。 根据您使用的Gatsby入门程序,这些可能已经安装。 检查package.json以查看情况。

安装 (Install)

We’re installing a few things here. Each play a different role in our image setup. We’ll go into further detail in a bit.

我们在这里安装一些东西。 每个在我们的图像设置中扮演不同的角色。 我们将进一步详细介绍。

$ npm install --save gatsby-image gatsby-transformer-sharp gatsby-plugin-sharp

组态 (Configuration)

Now we’ll add these to our gatsby-config.js.

现在,将它们添加到我们的gatsby-config.js

gatsby-config.js
gatsby-config.js
const path = require('path');

module.exports = {
  plugins: [
    ...
    'gatsby-plugin-sharp',
    'gatsby-transformer-sharp',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'images',
        path: path.join(__dirname, `src`, `images`),
      },
    },
  ],
}

Notice that we are configuring gatsby-source-filesystem as well. This is to create file nodes from our images so they’re available through graphql queries. For this guide, we’re placing our images in the src/images directory.

注意,我们也在配置gatsby-source-filesystem 。 这是根据我们的图像创建文件节点 ,以便可以通过graphql查询使用它们。 对于本指南,我们将图像放置在src/images目录中。

As for our other plugins:

至于我们的其他插件:

  • gatsby-plugin-sharp is a low-level helper that powers the connections between Sharp and gatsby-image. It also exposes several image processing functions.

    gatsby-plugin-sharp是一个底层助手,它为Sharpgatsby-image之间的连接提供了动力 。 它还公开了几种图像处理功能。

  • gatsby-transformer-sharp facilitates the creation of multiples images of the right sizes and resolutions.

    gatsby-transformer-sharp有助于创建正确大小和分辨率的倍数图像。

处理图像 (Working With Images)

Now that we’re set up, we can start working with images in our site. Let’s create a hero.js component to use with our images.

现在我们已经设置好了,我们可以开始在站点中处理图像了。 让我们创建一个hero.js组件以用于我们的图像。

src/components/hero.js
src / components / hero.js
import React from 'react';

export default ({ data }) => (
  <section>
    <div>
      <h1>Hi, I like websites.</h1>
      <p>Sometimes I make them.</p>
    </div>
  </section>
)

查询图像 (Querying Images)

The gatsby-transformer-sharp plugin creates nodes of type ImageSharp for us to query. They can be either fixed or fluid.

gatsby-transformer-sharp插件创建ImageSharp类型的节点供我们查询。 它们可以是fixed也可以是fluid

  • Fixed takes the width and heigh arguments in our queries and provides fixed-size images.

    固定在我们的查询中采用widthheigh参数,并提供固定大小的图像。

  • Fluid takes maxWidth and maxHeight as arguments in a query and provides responsive image sizes.

    Fluid在查询中将maxWidthmaxHeight作为参数,并提供响应的图像大小。

Both of these will have a number of varying file sizes that utilize the <picture> element to load the right file size based on media breakpoints.

这两个文件都有许多不同的文件大小,这些文件大小利用<picture>元素根据媒体断点加载正确的文件大小。

src/components/hero.js
src / components / hero.js
export const query = graphql`
  query {
    file(relativePath: { eq: "images/heroImage.jpg" }) {
      childImageSharp {
        fluid(maxWidth: 1600, maxHeight: 800) {
          ...GatsbyImageSharpFluid_withWebp
        }
      }
    }
  }
`

Our query includes the ...GatsbyImageSharpFluid_withWebp fragment, which essentially imports a few predetermined properties. You can read more about the available fragments in the gatsby-image Readme.

我们的查询包括...GatsbyImageSharpFluid_withWebp 片段 ,该片段实际上导入了一些预定的属性。 您可以在gatsby-image自述文件中阅读有关可用片段的更多信息。

You can run this query in GraphiQL to browse the several useful properties at your disposal.

您可以在GraphiQL中运行此查询以浏览一些有用的属性。

使用Gatsby图像组件 (Using the Gatsby Image Component)

Now that we have our query, let’s use it in the hero.js component we made earlier. We’ll need to import graphql from gatsby and Img from gatsby-image.

现在我们有了查询,让我们在前面制作的hero.js组件中使用它。 我们需要从gatsby导入graphql和从gatsby-image导入Img

src/components/hero.js
src / components / hero.js
import React from 'react';
import { graphql } from 'gatsby';
import Img from 'gatsby-image';

export default ({ data }) => (
  <section>
    <Img
      fluid={data.file.childImageSharp.fluid}
      alt="This is a picture of my face."
    />
    <div>
      <h1>Hi, I like websites.</h1>
      <p>Sometimes I make them.</p>
    </div>
  </section>
)

export const query = graphql`
  query {
    file(relativePath: { eq: "images/heroImage.jpg" }) {
      childImageSharp {
        fluid(maxWidth: 1600, maxHeight: 800) {
          ...GatsbyImageSharpFluid_withWebp
        }
      }
    }
  }
`

Aside from taking the alt prop, the Img component will also accept style and imgStyle as objects for adding custom styling to the parent container and img element, respectively. For a complete list, check out the component documentation.

除了采用alt道具外, Img组件还将接受styleimgStyle作为对象,以分别向父容器和img元素添加自定义样式。 有关完整列表,请参阅组件文档

Gatsby will render a responsive and lazy-loaded set of images. These will be compressed, have any unnecessary metadata stripped, and include a “blur-up” effect on load. Not bad!

Gatsby将渲染一组响应式和延迟加载的图像。 这些将被压缩,去除任何不必要的元数据,并对负载产生“模糊”效果。 不错!

Polyfill (Polyfill)

There’s also a polyfill available for the object-fit/object-position CSS properties. You can instead import from gatsby-image/withIEPolyfill. The component will tell Gatsby to automatically apply the object-fit-images polyfill to your image.

还有一个针对对象适合/对象位置 CSS属性的polyfill。 您可以改为从gatsby-image/withIEPolyfill 。 该组件将告诉Gatsby将object-fit-images polyfill自动应用于您的图像。

src/components/hero.js
src / components / hero.js
import React from 'react';
import { graphql } from 'gatsby';
import Img from 'gatsby-image/withIEPolyfill';

export default ({ data }) => (
  <section>
    <Img
      fluid={data.file.childImageSharp.fluid}
      objectFit="cover"
      objectPosition="50% 50%"
      alt="This is a picture of my face."
    />
    ...
  </section>
)

...

影像压缩 (Image Compression)

By default, gatsby-plugin-sharp uses various compression libraries. But there are a few options we can set if we’d like to modify the default behavior.

默认情况下, gatsby-plugin-sharp使用各种压缩库。 但是,如果我们想修改默认行为,可以设置一些选项。

gatsby-config.js
gatsby-config.js
module.exports = {
  plugins: [
    ...
    {
      resolve: 'gatsby-plugin-sharp',
      options: {
        useMozJpeg: false,
        stripMetadata: true,
        defaultQuality: 75,
      },
    },
  ],
}

We can optionally use MozJPEG for even better JPEG compression. However, keep in mind that this will likely significantly increase your build time.

我们可以选择使用MozJPEG以获得更好的JPEG压缩。 但是,请记住,这可能会大大增加您的构建时间。

Check out the plugin’s documentation for all the available methods to modify and optimize your images.

查看插件的文档以获取所有可用的方法来修改和优化图像。

结论 (Conclusion)

This is only scratching the surface of what you can do with images in Gatsby. Whether you’re looking to squeeze out as much performance as possible or create a quality experience for your users, Gatsby’s rich toolset has you covered. I encourage you to read all the linked resources and play around with the plugins to find what best suits your needs.

这仅是您在盖茨比中处理图像所能做的事情的表面。 无论您是想寻求尽可能多的性能还是为用户创造优质的体验,盖茨比的丰富工具集都可以满足您的需求。 我鼓励您阅读所有链接的资源并尝试使用插件,以找到最适合您的需求的插件。

翻译自: https://www.digitalocean.com/community/tutorials/gatsbyjs-images-in-gatsby

gatsby

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值