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

如何为 Gatsby 博客文章添加响应式封面图片(教程)

如何为 Gatsby 博客文章添加响应式封面图片

操作说明

结果

在这篇文章中,我将介绍如何为你的博客文章添加全尺寸图片封面。

Gatsby 的好处在于,我们可以通过插件轻松实现这一点,而无需手动为不同屏幕尺寸提供不同的图片。每个设备都会收到其优化后的封面版本。真棒!

这篇文章是“ Gatsby 性能提升 10 倍”系列的一部分,我将在其中分享我个人关于 Gatsby 调优、增强和优化的经验。我还会发布更多关于 Gatsby 调优的精彩内容。敬请期待!

假设

我假设您已经设置好了 Markdown。这意味着您已经安装并配置了以下插件:

  • gatsby-source-filesystem
  • gatsby-transformer-remark

操作说明

1. 编辑配置

请确保已在配置文件中设置插件。

// gatsby-config.js
module.exports = {
  /*
    ...
  */
  plugins: [
    /*
    ...
    */
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 620,
            },
          },
        ],
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    /*
      ...
    */
  ],
}
Enter fullscreen mode Exit fullscreen mode

#2. 更新 Markdown 文件

将图片放在 markdown 文件附近,并更新 markdown 文件(在我的例子中是post.md),使cover字段指向图片。

---
title: 'How Failing With Pomodoro Technique Made Me 2x Better Programmer'
date: '2019-03-27'
cover: './cover.png'
---
Enter fullscreen mode Exit fullscreen mode

现在让我们更新一下GraphQL查询。

#3. 更新 GraphQL 查询

blog-post.js

const query = graphql`
  query BlogPostBySlug($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      id
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        title
        cover {
          publicURL
          childImageSharp {
            sizes(maxWidth: 2000) {
              ...GatsbyImageSharpSizes
            }
          }
        }
      }
    }
  }
`
Enter fullscreen mode Exit fullscreen mode

现在您可以编辑组件代码了。

#4. 更新 React 组件

请确保您已gatsby-image安装该组件。该组件将处理所有响应式设计相关的功能。

yarn add gatsby-image
Enter fullscreen mode Exit fullscreen mode

为了显示全尺寸图像,我正在将cover数据传递给我的Layout组件。

<Layout
  location={props.location}
  title={siteTitle}
  cover={data.frontmatter.cover}
>
  {/* ... */}
</Layout>
Enter fullscreen mode Exit fullscreen mode

然后我在布局组件中显示这些数据。

import Img from 'gatsby-image'
Enter fullscreen mode Exit fullscreen mode

组件的使用非常简单。以下是我的做法Layout.js

!!cover ? <Img sizes={cover.childImageSharp.sizes} /> : null
Enter fullscreen mode Exit fullscreen mode

结果

以下是通过这些简单步骤可以得到的结果示例。

现在,您可以拥有这款外观炫酷、针对所有设备优化、加载速度快的保护壳,您一定会感到满意。

嘿!这只是“十倍提升的盖茨比”系列中的一篇。让我来告诉你你会喜欢它的原因,来看看吧!

文章来源:https://dev.to/rohovdmytro/how-to-add-responsive-cover-images-to-gatsby-blog-posts-2n2m