一、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>