Skip to content
るいラボ
原神ツール

Gatsby×ブログ - 画像を使い回す方法

Gatsby1 min read

やりたいこと

  • 使い回す画像を1箇所にまとめておきたい
  • 記事に画像を入れるときは,できるだけ簡単にしたい

コンポーネントを作る

{プロジェクト}/img/my-iconとなるフォルダを作成

gatsby-config.js
1module.exports = {
2 plugins: [
3 {
4 resolve: `gatsby-plugin-alias-imports`,
5 options: {
6 alias: {
7 "@components": "src/components",
8 },
9 extensions: ["js", "jsx", "ts", "tsx"],
10 },
11 },
12 {
13 resolve: `gatsby-source-filesystem`,
14 options: {
15 name: `img`,
16 path: `${__dirname}/img/`,
17 },
18 },
19 `gatsby-plugin-image`,
20 `gatsby-plugin-sharp`,
21 `gatsby-transformer-sharp`,
22 ].filter(Boolean),
23}
{プロジェクト}/src/components/img.tsx
1import * as React from "react"
2import { useStaticQuery, graphql } from "gatsby"
3import { GatsbyImage, IGatsbyImageData, getImage } from "gatsby-plugin-image"
4
5type ImgStatic = {
6 allFile: {
7 nodes: {
8 relativeDirectory: string
9 name: string
10 childImageSharp: {
11 gatsbyImageData: IGatsbyImageData
12 }
13 }[]
14 }
15}
16
17type ImgProps = {
18 folder?: string
19 name: string
20 width?: string
21}
22
23const Image = (props: ImgProps) => {
24 const data = useStaticQuery<ImgStatic>(graphql`
25 {
26 allFile(filter: {sourceInstanceName: {eq: "img"}}) {
27 nodes {
28 relativeDirectory
29 name
30 childImageSharp {
31 gatsbyImageData
32 }
33 }
34 }
35 }
36 `)
37 const img = data.allFile.nodes.find(e => ((!props.folder && !e.relativeDirectory) || e.relativeDirectory == props.folder) && e.name == props.name)
38 if(img) return <GatsbyImage image={getImage(img)} alt={img.name} style={{width: props.width}} />
39 else return <div>Not Found</div>
40}
41
42export default Image
43
44export const MyIcon = (props: ImgProps) => {
45 return <Image folder="my-icon" {...props} />
46}
投稿記事
1---
2/*** Frontmatter ***/
3---
4
5import Img, { MyIcon } from "@components/img"
6
7## 記事
8
9<Img folder="my-icon" name="chara-icon" />
10
11<MyIcon name="chara-icon" />
12
13## きじ

MyIconfolder="my-icon"を書かずにすむ.
使用頻度が高いものを使う時用.

※見様見真似で作ったプログラムなので,上手く行かないときはごめんなさい.

Tips

  • 画像を入れる img フォルダは基本どこでもOK.
    gatsby-config.js の filesystem > path の修正もすること.
  • gatsby-plugin-alias-importsのプラグインはお好みで.
  • filesystem の name は GraphQL のフィルターで使う名前.
  • <Img name="chara-icon" />のようにImgでフォルダ指定しない場合,imgフォルダ直下の画像を見るようにしている.
  • styleで幅指定をしている.ほかにも色々できると思う.

Gatsby