GraphQL
The next part is making sure you actually use the plugins you have defined in the config. It may seem odd to mention this, but simply querying for the most obvious image properties will result in doing the optimizing work without any of the benefits.
For example, here is a common graphql query example for simply including image URL. Pay special attention to the banner property, which represents an image included in resource (in this case markdown source).
export const pageQuery = graphql`
query ResourceIndexQuery {
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
totalCount
edges {
node {
id
frontmatter {
title
date(formatString: "DD MMMM, YYYY")
category
banner {
publicURL
}
}
fields {
slug
}
excerpt
}
}
}
}
`;
In the above code, we reasonably assume that to display the image on our site, we should extract the publicURL from the field we have defined for our image. This displays the image, but does so at the original resolution.
To leverage the Sharp plugins we need to extract the image URL differently. See the changes below for the banner field.
export const pageQuery = graphql`
query ResourceIndexQuery {
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
totalCount
edges {
node {
id
frontmatter {
title
date(formatString: "DD MMMM, YYYY")
category
banner {
childImageSharp {
fluid(maxHeight: 500) {
...GatsbyImageSharpFluid
}
}
}
}
fields {
slug
}
excerpt
}
}
}
}
`;
We are now replacing publicURL with
childImageSharp {
fluid(maxHeight: 500) {
...GatsbyImageSharpFluid
}
}
Fluid indicates that Gatsby.js will make a number of resolutions that can be used for various client window sizes. (fixed is also an option)
We use the "spread" operator to make all the properties accessible of GatsbyImageSharpFluid which is required to implement gatsby-image below.