由于 gatsby-image 已被弃用,推荐使用 gatsby-plugin-image,因此我尝试解释其使用方法
「gatsby-image(gatsby-imageパッケージ)目前已经被弃用。」
听说推荐使用 gatsby-plugin-image,所以我决定使用它。
虽然使用体验稍有不同,但比以前更方便了。
成果物和概述


gatsby-plugin-image插件使用StaticImage和GatsbyImage两个组件。
StaticImage 使用相对路径即可立即获取到优化后的图像,非常方便易用。且无需使用 GraphQL。
GatsbyImage使用了从GraphQL中拉取的数据。我认为这样更接近于使用gatsby-image的方式。
我认为,当需要大量图像或者不必拉取GraphQL时,使用StaticImage是个不错的选择(如果有更好的选择方法,我想了解一下)。
下手
安装
首先创建一个项目。
gatsby new GatsbyPluginTest https://github.com/gatsbyjs/gatsby-starter-hello-world
如果没有安装gatsby-cli的人需要单独安装。
安装相关插件。
yarn add gatsby-plugin-image gatsby-plugin-sharp gatsby-transformer-sharp gatsby-source-filesystem
绘画。
使用o-dan,在任意的名字下保存免费素材图片。
gatsby-config.js的配置
module.exports = {
plugins: [
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images/`,
},
},
],
}
源代码目录结构
src
images
shiva.jpeg(任意の画像)
pages
index.js
使用StaticImage的方法
只需指定静态图像的相对路径,所以非常简单。
import React from "react";
import { StaticImage } from "gatsby-plugin-image";
const Home = () => {
return (
<div>
<h1>Hello world!</h1>
<StaticImage
src="../images/shiva.jpeg" // 相対パス
width={600}
alt="Shiva"
placeholder="blurred" // ボヤッと読み込ませるオプション。他にもいくつかある
quality="40" // 画質
/>
</div>
);
}
export default Home;
我觉得可能不需要特别解释。
使用GatsbyImage的方法
我会使用GraphQL,并从库中获取GatsbyImage和getImage方法。 我将使用getImage方法将其用于GatsbyImage组件的src属性image属性。
import React from "react";
import { GatsbyImage, getImage } from "gatsby-plugin-image";
import { graphql } from "gatsby";
const Home = ({ data }) => { // graphqlでデータを引っ張ると data に 返り値 が返ってくる
const GatsbyImages = data.allFile.edges.map(({node}) => {
return <GatsbyImage image={getImage(node.childImageSharp)} alt={node.name} key={node.name} />
})
return (
<div>
<h1>Hello world!</h1>
{GatsbyImages}
</div>
);
}
export const query = graphql`
query MyQuery {
allFile {
edges {
node {
name // altとkey属性用
childImageSharp {
gatsbyImageData(
blurredOptions: {width: 100} // blurオプション。widthを小さくした方がblurっぽいかなと
width: 600
placeholder: BLURRED // blurup
)
}
}
}
}
}
`;
export default Home;
我试着把两个放在一起。

并无特别的意义