一、Gatsby页面怎么加载图片?

在编写网站页面时,总是会遇到有图片要显示,那么怎么加载这些图片呢?

1、Gatsby 中图片有三种形式:
  • 本地图片,譬如 : src/images 目录下的图片;
  • 远程网络图片,譬如 :https://learn-anything.cn/static/cf1d0cf910dcc988ea869d56609eca53/096ec/bainian.webp
  • Gatsby 数据层中的图片节点。

二、加载本地和网络图片

Gatsby 下是通过 StaticImage 组件来加载图片。

1、StaticImage
  • 安装插件

    npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem
  • 增加配置

    // gatsby-config.js
    module.exports = {
      siteMetadata: {
        title: "My First Gatsby Site",
      },
      plugins: [
        "gatsby-plugin-image",
        "gatsby-plugin-sharp",
      ],
    };
  • 显示图片

    StaticImage 是 gatsby-plugin-image 提供的组件,类似html 中的 img 标签,可以在页面中直接使用。

    import * as React from 'react'
    import Layout from '../components/layout'
    import { StaticImage } from 'gatsby-plugin-image'
    import bainian from "../images/bainian.jpg"
    
    const IndexPage = () => {
        return (
            <Layout pageTitle="Home Page">
                <p>I'm making this by following the Gatsby Tutorial.</p>
                <StaticImage
                    alt="网络图片"
                    src="https://learn-anything.cn/static/cf1d0cf910dcc988ea869d56609eca53/096ec/bainian.webp"
                />
                <StaticImage
                    alt="本地图片"
                    src="../images/bainian.jpg"
                />
                      <img alt="img显示本地图片" src={bainian} />
            </Layout>
        )
    }
    
    export default IndexPage

2、StaticImage 与 img
  • <img/><StaticImage/> 区别 :StaticImage 组件对图像做了预处理,会根据显示器不同而选择适合的分辨率进行图片渲染,无需下载原图,加快显示速度也节约网络流量。
  • <img/> 在 gatsby 中的使用实例:

    import React from "react"
    import logo from "./logo.png" // 这里告诉 Webpack 这个 JS 文件用了这张图片
    console.log(logo) // /logo.84287d09.png
    function Header() {
      // 引入得到的是你的图片 URL
      return <img src={logo} alt="Logo" />
    }
    export default Header

3、borderRadius 失效

如下使用 style 中的 borderRadius 给图片增加圆角边框,此法在 safari 浏览器会失效。

<StaticImage src="../images/bainian.jpg" alt="百念牙膏" style={{border: 'solid 1px #ddd', borderRadius: 10}}/>

解决方案:用 imgStyle 代替 style。

<StaticImage src="../images/bainian.jpg" alt="百念牙膏" imgStyle={{border: 'solid 1px #ddd', borderRadius: 10}}/>

三、加载数据层图片节点

数据层图片节点称之为动态图片,在项目启动时,gatsby会自动从源数据中下载图片,并转换为数据层中图片节点,下面详解 图片文件 -> 数据层图片节点 的过程。

1、原理说明:
  • 本地文件通过 gatsby-source-filesystem 插件,转为数据层节点 allFile;
  • 数据层节点 allFile 中的图像节点, 通过 gatsby-transformer-sharp 插件,转为数据层节点 ImageSharp;
  • 使用 Graphql 查询 ImageSharp 节点数据,传递给 gatsby-plugin-image 插件提供的组件 GatsbyImage 进行显示。
  • 【备注】:gatsby-transformer-sharp 插件会为所有数据层节点的image属性增加 ImageSharp 图片节点。譬如 gatsby-source-strapi 插件从strapi 获取数据生成 allStrapiArticles 节点,gatsby-transformer-sharp 也会为其 image 属性自动生成图片节点:image.localFile.childImageSharp.

ImageSharp


四、显示 数据层图片节点
1、实例情况说明

gatsby 项目中有 src/mdx/my-first-post.mdx 文件 和 src/mdx/christopher-ayme-ocZ-_Y7-Ptg-unsplash.jpg 图片,写一个页面可以展示其数据和图片。

// src/mdx/my-first-post.mdx
---
title: "My First Post"
date: "2021-07-23"
hero_image: "./christopher-ayme-ocZ-_Y7-Ptg-unsplash.jpg"
hero_image_alt: "A gray pitbull relaxing on the sidewalk with its tongue hanging out"
hero_image_credit_text: "Christopher Ayme"
hero_image_credit_link: "https://unsplash.com/photos/ocZ-_Y7-Ptg"
---

This is my first blog post! Isn't it *great*?
Some of my **favorite** things are:
* Petting dogs
* Singing
* Eating potato-based foods

2、解决方案
  • 第一步:把 .mdx 文件转换为 MDX 数据节点,安装下面插件

    npm install gatsby-source-filesystem gatsby-plugin-mdx @mdx-js/mdx @mdx-js/react gatsby-transformer-sharp gatsby-plugin-image
  • 第二步:修改 gatsby-config.js 中的配置

    // gatsby-config.js
    module.exports = {
      plugins: [
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            name: `posts`,
            path: `${__dirname}/src/mdx/`,
          },
        },
        {
          resolve: `gatsby-plugin-mdx`,
          options: {
            extensions: [`.mdx`, `.md`]
          },
        },
        "gatsby-transformer-sharp",
        "gatsby-plugin-image"
      ],
    }
  • 第三步:新建页面 src/pages/first-post.js,页面的名字来之 .mdx 文件对应mdx 节点的slug属性(mdx路由规则)。

    import * as React from 'react'
    import { graphql } from 'gatsby'
    import { MDXRenderer } from 'gatsby-plugin-mdx'
    import { GatsbyImage, getImage } from 'gatsby-plugin-image'
    
    const BlogPost = ({ data }) => {
    
      console.log("BlogPost :", data);
      const image = getImage(data.mdx.frontmatter.hero_image)
    
      return (
        <div >
          <p>Title: {data.mdx.frontmatter.title}</p>
          <p>Posted: {data.mdx.frontmatter.date}</p>
          <GatsbyImage
            image={image}
            alt={data.mdx.frontmatter.hero_image_alt}
          />
          <MDXRenderer>
            {data.mdx.body}
          </MDXRenderer>
        </div>
      )
    }
    
    export const query = graphql`
        query($id: String) {
          mdx(id: {eq: $id}) {
            body
            frontmatter {
              title
              hero_image_alt
              hero_image_credit_link
              hero_image_credit_text
              hero_image {
                childImageSharp {
                  gatsbyImageData
                }
              }
            }
          }
        }
      `
    
    export default BlogPost
  • 第四步:浏览器访问:http://localhost:8000/first-blog,查看页面显示图片和 .mdx 内容。

五、显示 strapi 中包含的图片
1、问题说明

strapi 是可视化的 CMS(内容管理系统),markdown编辑的文档,可以很方便存储在 strapi中,且提供了RestApi访问存储是数据。怎么在gatsby中访问 strapi 中数据?


2、解决方案

借助插件 gatsby-source-strapi 把strapi中数据转为 gatsby 数据节点,方便访问。

  • 第一步:把 strapi 中 articles 数据转换为 gatsby 数据节点,安装下面插件

    npm install gatsby-source-strapi gatsby-transformer-sharp gatsby-plugin-image
  • 第二步:修改 gatsby-config.js 中的配置

    // gatsby-config.js
    module.exports = {
      plugins: [
        {
          resolve: `gatsby-source-strapi`,
          options: {
            // apiURL: "http://localhost:1337",
            queryLimit: 1000,
            collectionTypes: [`articles`],
          },
        },
        "gatsby-transformer-sharp",
        "gatsby-plugin-image"
      ],
    }
  • 第三步:新建页面 src/pages/homepage.js

    import * as React from "react"
    import { graphql } from "gatsby"
    import { GatsbyImage } from "gatsby-plugin-image"
    
    const HomePage = ({ data }) => {
        return (
            <GatsbyImage image={data.strapiArticles.image.localFile.childImageSharp.gatsbyImageData} />
        )
    }
    
    export default HomePage
    
    export const query = graphql`{
        strapiArticles {
            image {
              localFile {
                childImageSharp {
                  gatsbyImageData
                }
              }
            }
          }
      }
    `
  • 第四步:浏览器访问:http://localhost:8000/homepage,查看内容

六、参考文档

Learn_anything
7 声望0 粉丝

收集互联网优质资源!