Using Gatsby Image Plugin

gatsby logo

graphql logo react logo


This relates to a previous post Updated To Gatsby v3

Migrating to gatsby-plugin-image seemed pretty easy but there was a bug with the way global is implemented in the plugin which caused other components to break.

๐Ÿ“ Gatsby Image Plugin on Gatsby Documentation

Migrating to Image Plugin

There are a few steps to migrating an existing site to use the plugin.

  • add gatsby-plugin-image and remove gatsby-image ๐Ÿ“ฆ
  • enable gatsby-plugin-image in main gatsby config ๐Ÿ“ท
  • change graphql query in post template for gatsbyImageData
  • change graphql query in page template for gatsbyImageData
  • import gatsby-plugin-image & replaced Img with GatsbyImage in post component
  • import gatsby-plugin-image & replaced Img with GatsbyImage in page component

Fix bug introduced by gatsby-plugin-image

  • fix problem with gatsby-plugin-image & webpack 5

Gatsby Image Plugin pull request on github

GraphQL Queries

Changes to the graphql image queries were pretty easy.

image {
  childImageSharp {
-    fluid(maxWidth: 1200) {
-      ...GatsbyImageSharpFluid
-    }
+    gatsbyImageData(layout: FULL_WIDTH)
  }
}

Replacing Img with GatsbyImage

Replace import from gatsby-image with gatsby-plugin-image

-import Img from 'gatsby-image'
+import { GatsbyImage } from 'gatsby-plugin-image'

Replace Img elements with GatsbyImage elements referencing new GraphQL query data.

-<Img fluid={image.childImageSharp.fluid} />
+<GatsbyImage image={image.childImageSharp.gatsbyImageData} />

Fix Bug

After doing all of the above everything seems ok ?
Possibly but if you check the console you may find errors with react components referencing global.

โš ๏ธ Warning

If you use 'global' in any plugins or components they will fail with 'global is not defined' due to gatsby-plugin-image.

As a workaround define global in gatsby-browser.js.

window.global = window

Everything should now be working, including plugins & components referencing global.

๐Ÿ“ฆ Update

The global bug is now fixed in gatsby-plugin-image@1.2.1
There should be no need to define window.global in gatsby-browser.js.

gatsbyjs/gatsby@a5869e3

The source for the site is available on github.

equk-gatsby