Working with images in GatsbyJS

install npm deps:

1
npm install --save gatsby-transformer-sharp gatsby-plugin-sharp gatsby-image

In gatsby-config.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
  plugins: [
  	// ...
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
	// ...
	{
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/images`,
        name: "images",
      },
    },
	// ...
  ]

Display photo

In Layout.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import Img from "gatsby-image"
// ...

const Layout = ({ children }: { children: React.ReactNode }) => {
  // ...
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      file(relativePath: { regex: "/bg-post/" }) {
        childImageSharp {
          fluid(maxWidth: 1000) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  `)
  
  return (
  	<>
	  <Img fluid={data.file.childImageSharp.fluid}></Img>
	</>
  )