Gatsby中怎么加载图片?

一、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>
        )
    
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值