Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
gatsby-plugin-image
Advanced tools
Adding responsive images to your site while maintaining high performance scores can be difficult to do manually. The Gatsby Image plugin handles the hard parts of producing images in multiple sizes and formats for you!
gatsby-plugin-image is a powerful image optimization plugin for Gatsby, a React-based framework. It provides a set of React components and GraphQL fragments to optimize and load images in a performant way, ensuring that images are loaded quickly and efficiently.
StaticImage
The StaticImage component is used for static images that are known at build time. It provides a simple way to add optimized images to your site with various layout options like fixed, fluid, and constrained.
import { StaticImage } from 'gatsby-plugin-image';
const MyComponent = () => (
<StaticImage
src="../images/my-image.jpg"
alt="A descriptive alt text"
placeholder="blurred"
layout="fixed"
width={300}
height={200}
/>
);
GatsbyImage
The GatsbyImage component is used for dynamic images that are queried at runtime. It provides advanced image optimization features and supports various layout options. The getImage helper function is used to extract the image data from the GraphQL query.
import { GatsbyImage, getImage } from 'gatsby-plugin-image';
import { graphql, useStaticQuery } from 'gatsby';
const MyComponent = () => {
const data = useStaticQuery(graphql`
query {
file(relativePath: { eq: "my-image.jpg" }) {
childImageSharp {
gatsbyImageData(layout: CONSTRAINED, placeholder: BLURRED, width: 300)
}
}
}
`);
const image = getImage(data.file.childImageSharp.gatsbyImageData);
return <GatsbyImage image={image} alt="A descriptive alt text" />;
};
Image Processing with GraphQL
This feature allows you to use GraphQL to query image data and process it with Sharp, a high-performance image processing library. The queried image data can then be used with the GatsbyImage component to render optimized images.
export const query = graphql`
query {
file(relativePath: { eq: "my-image.jpg" }) {
childImageSharp {
gatsbyImageData(layout: CONSTRAINED, placeholder: BLURRED, width: 300)
}
}
}
`;
const MyComponent = ({ data }) => {
const image = getImage(data.file.childImageSharp.gatsbyImageData);
return <GatsbyImage image={image} alt="A descriptive alt text" />;
};
react-image is a lightweight React component for loading images. It provides basic features like lazy loading and error handling but lacks the advanced image optimization and GraphQL integration provided by gatsby-plugin-image. It is suitable for simpler use cases where advanced optimization is not required.
react-lazy-load-image-component is a React component for lazy loading images. It focuses on providing a simple and efficient way to lazy load images with support for placeholders and effects. While it does not offer the same level of optimization as gatsby-plugin-image, it is a good choice for projects that need basic lazy loading functionality.
Adding responsive images to your site while maintaining high performance scores can be difficult to do manually. The Gatsby Image plugin handles the hard parts of producing images in multiple sizes and formats for you!
For full documentation on all configuration options, see the Gatsby Image Plugin reference guide
gatsby-plugin-image
and gatsby-plugin-sharp
. Additionally install gatsby-source-filesystem
if you are using static images, and gatsby-transformer-sharp
if you are using dynamic images.npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-sharp
gatsby-config.js
:module.exports = {
plugins: [
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`, // Needed for dynamic images
],
}
The Gatsby Image plugin includes two image components: one for static and one for dynamic images. An effective way to decide which you need is to ask yourself: "will this image be the same every time the component or template is used?". If it will always be the same, then use StaticImage
. If it will change, whether through data coming from a CMS or different values passed to a component each time you use it, then it is a dynamic image and you should use the GatsbyImage
component.
If you are using an image that will be the same each time the component is used, such as a logo or front page hero image, you can use the StaticImage
component. The image can be a local file in your project or an image hosted on a remote server. Any remote images are downloaded and resized at build time.
Add the image to your project.
If you are using a local image, copy it into the project. A folder such as src/images
is a good choice.
Add the StaticImage
component to your template.
Import the component, then set the src
prop to point to the image you added earlier. The path is relative to the source file itself. If your component file was src/components/dino.js
, then you would load the image like this:
import { StaticImage } from "gatsby-plugin-image"
export function Dino() {
return <StaticImage src="../images/dino.png" alt="A dinosaur" />
}
If you are using a remote image, pass the image URL in the src
prop:
import { StaticImage } from "gatsby-plugin-image"
export function Kitten() {
return <StaticImage src="https://placekitten.com/800/600" alt="A kitten" />
}
When you build your site, the StaticImage
component will load the image from your filesystem or from the remote URL, and it will generate all the sizes and formats that you need to support a responsive image.
Because the image is loaded at build time, you cannot pass the filename in as a prop, or otherwise generate it outside of the component. It should either be a static string, or a local variable in the component's scope.
Important: Remote images are downloaded and resized at build time. If the image is changed on the other server, it will not be updated on your site until you rebuild.
Configure the image.
You configure the image by passing props to the <StaticImage />
component. You can change the size and layout, as well as settings such as the type of placeholder used when lazy loading. There are also advanced image processing options available. You can find the full list of options in the API docs.
import { StaticImage } from "gatsby-plugin-image"
export function Dino() {
return (
<StaticImage
src="../images/dino.png"
alt="A dinosaur"
placeholder="blurred"
layout="fixed"
width={200}
height={200}
/>
)
}
This component renders a 200px by 200px image of a dinosaur. Before loading it will have a blurred, low-resolution placeholder. It uses the "fixed"
layout, which means the image does not resize with its container.
StaticImage
There are a few technical restrictions to the way you can pass props into StaticImage
. Most importantly, you can't use any of the parent component's props. For more information, refer to the Gatsby Image plugin reference guide. If you find yourself wishing you could use a prop passed from a parent for the image src
then it's likely that you should be using a dynamic image.
If you need to have dynamic images (such as if they are coming from a CMS), you can load them via GraphQL and display them using the GatsbyImage
component.
Add the image to your page query.
Any GraphQL File object that includes an image will have a childImageSharp
field that you can use to query the image data. The exact data structure will vary according to your data source, but the syntax is like this:
query {
blogPost(id: { eq: $Id }) {
title
body
avatar {
childImageSharp {
gatsbyImageData(width: 200)
}
}
}
}
Configure your image.
For all the configuration options, see the Gatsby Image plugin reference guide.
You configure the image by passing arguments to the gatsbyImageData
resolver. You can change the size and layout, as well as settings such as the type of placeholder used when lazy loading. There are also advanced image processing options available. You can find the full list of options in the API docs.
query {
blogPost(id: { eq: $Id }) {
title
body
author
avatar {
childImageSharp {
gatsbyImageData(
width: 200
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
)
}
}
}
}
Display the image.
You can then use the GatsbyImage
component to display the image on the page. The getImage()
function is an optional helper to make your code easier to read. It takes a File
and returns file.childImageSharp.gatsbyImageData
, which can be passed to the GatsbyImage
component.
import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
function BlogPost({ data }) {
const image = getImage(data.blogPost.avatar)
return (
<section>
<h2>{data.blogPost.title}</h2>
<GatsbyImage image={image} alt={data.blogPost.author} />
<p>{data.blogPost.body}</p>
</section>
)
}
export const pageQuery = graphql`
query {
blogPost(id: { eq: $Id }) {
title
body
author
avatar {
childImageSharp {
gatsbyImageData(
width: 200
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
)
}
}
}
}
`
For full APIs, see Gatsby Image plugin reference guide.
You might find yourself using the same options (like placeholder
, formats
etc.) with most of your GatsbyImage
and StaticImage
instances.
You can customize the default options with gatsby-plugin-sharp
.
The following configuration describes the options that can be customized along with their default values:
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-sharp`,
options: {
defaults: {
formats: [`auto`, `webp`],
placeholder: `dominantColor`,
quality: 50,
breakpoints: [750, 1080, 1366, 1920],
backgroundColor: `transparent`,
tracedSVGOptions: {},
blurredOptions: {},
jpgOptions: {},
pngOptions: {},
webpOptions: {},
avifOptions: {},
}
}
},
`gatsby-transformer-sharp`,
`gatsby-plugin-image`,
],
}
Main article: Migrating from gatsby-image to gatsby-plugin-image
If your site uses the old gatsby-image
component, you can use a codemod to help you migrate to the new Gatsby Image components. This can update the code for most sites. To use the codemod, run this command in the root of your site:
npx gatsby-codemods gatsby-plugin-image
This will convert all GraphQL queries and components to use the new plugin. For more details, see the migration guide.
FAQs
Adding responsive images to your site while maintaining high performance scores can be difficult to do manually. The Gatsby Image plugin handles the hard parts of producing images in multiple sizes and formats for you!
The npm package gatsby-plugin-image receives a total of 92,090 weekly downloads. As such, gatsby-plugin-image popularity was classified as popular.
We found that gatsby-plugin-image demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 7 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.