Skip to content

Commit 7142cfa

Browse files
ascorbicLB
and
LB
authored
docs(gatsby-plugin-image): Update readme (#27945)
* Update readme * Apply suggestions from code review Co-authored-by: LB <[email protected]> * Change from review Co-authored-by: LB <[email protected]>
1 parent 3183b66 commit 7142cfa

File tree

1 file changed

+58
-127
lines changed

1 file changed

+58
-127
lines changed

packages/gatsby-plugin-image/README.md

+58-127
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,40 @@
1-
# Experimental image plugin
1+
# gatsby-plugin-image (beta)
22

3-
This plugin is a replacement for gatsby-image. It adds [static images](#static-images), and a [new higher-performance gatsby-image component](#gatsby-image-next-generation).
4-
It also adds [a new GraphQL resolver](#graphql-resolver) to gatsby-transformer-sharp
3+
This plugin is a replacement for gatsby-image. It adds [static images](#staticimage), and a [new higher-performance gatsby-image component](#gatsbyimage). It also adds [a new GraphQL resolver](#graphql-resolver) to gatsby-transformer-sharp.
54

6-
This package is in alpha, and the API will change. It is not ready for production use yet, but feedback would be great.
5+
## Contents
6+
7+
- [StaticImage](#staticimage) - the new static image component
8+
- [GatsbyImage](#gatsbyimage) - a high-performance gatsby-image component
9+
- [gatsbyImageData](#graphql-resolver) - a simpler GraphQL API
710

811
## Usage
912

10-
Install `gatsby-plugin-image` and `gatsby-plugin-sharp`, then add them to your `gatsby-config.js`. Upgrade `gatsby` to at least `2.24.78`.
13+
1. Install `gatsby-plugin-image` and `gatsby-plugin-sharp`:
1114

12-
# Static images
15+
```shell
16+
npm install gatsby-plugin-image gatsby-plugin-sharp
17+
```
1318

14-
This plugin is a proof of concept for a simpler way to use Gatsby's image processing tools and components without needing to write GraphQL queries. It is designed for static images such as logos rather than ones loaded dynamically from a CMS.
19+
If you're using the new `GatsbyImage` in addition to `StaticImage`, you'll also want to install `gatsby-transformer-sharp`.
1520

16-
The old way to do this is with `useStaticQuery`:
21+
2. Upgrade `gatsby` to at least `2.24.78`.
1722

18-
```js
19-
import React from "react"
20-
import Img from "gatsby-image"
21-
22-
export const Dino = () => {
23-
const data = useStaticQuery(graphql`
24-
query LogoQuery {
25-
file(relativePath: { eq: "trex.png" }) {
26-
childImageSharp {
27-
fixed(height: 100) {
28-
...GatsbyImageSharpFixed
29-
}
30-
}
31-
}
32-
}
33-
`)
23+
3. Add the plugins to your `gatsby-config.js`:
3424

35-
return <Img fixed={data?.file?.childImageSharp?.fixed} alt="T-Rex" />
25+
```javascript
26+
module.exports = {
27+
plugins: [
28+
`gatsby-plugin-image`,
29+
`gatsby-plugin-sharp`,
30+
// `gatsby-transformer-sharp`
31+
],
3632
}
3733
```
3834

39-
Using this plugin, the code above can be written as follows:
35+
# StaticImage
36+
37+
This component is a new, simpler way to use Gatsby's image processing tools and components without needing to write GraphQL queries. It is designed for static images such as logos rather than ones loaded dynamically from a CMS.
4038

4139
```js
4240
import React from "react"
@@ -49,7 +47,7 @@ export const Dino = () => (
4947

5048
The `src` prop is relative to the source file, like in static HTML.
5149

52-
You can pass the same options as those available via `ImageSharp` queries:
50+
You can pass the same options as those available via [`gatsbyImageData`](#graphql-resolver) queries:
5351

5452
```js
5553
import React from "react"
@@ -60,53 +58,30 @@ export const Dino = () => (
6058
src="trex.png"
6159
placeholder="none"
6260
layout="fluid"
63-
grayscale
6461
maxWidth={200}
6562
alt="T-Rex"
63+
transformOptions={{ grayscale: true }}
6664
/>
6765
)
6866
```
6967

70-
...is equivalent to:
71-
72-
```js
73-
import React from "react"
74-
import Img from "gatsby-image"
75-
76-
export const Dino = () => {
77-
const data = useStaticQuery(graphql`
78-
query LogoQuery {
79-
file(relativePath: { eq: "trex.png" }) {
80-
childImageSharp {
81-
fluid(maxWidth: 200, grayscale: true) {
82-
...GatsbyImageSharpFixed_withWebp_noBase64
83-
}
84-
}
85-
}
86-
}
87-
`)
88-
89-
return <Img fixed={data?.file?.childImageSharp?.fixed} alt="T-Rex" />
90-
}
91-
```
92-
93-
## How does it work?
94-
95-
When your site is compiled, any references to StaticImage components are extracted, the images are resized by Sharp in a similar way to `gatsby-transformer-sharp`, and then the resulting sharp object is written to `.cache/caches/gatsby-plugin-image/`, with the filename generated as a hash of the normalized image props. Next, a Babel plugin finds any references to StaticImage, calculates the same hash, then adds a `require()` to that JSON file as a new `__imageData` prop. It then returns a GatsbyImage using that **imageData. Errors don't cause the build to fail, but instead are written to the component as an `**error` prop, which is then logged in develop.
96-
9768
### Are there restrictions to how this is used?
9869

99-
The props must be able to be statically-analyzed at build time. You can't pass them as props from outside the component, or use the results of function calls, for example.
70+
Because the images still need to be resized during build, the props must be able to be statically-analyzed at build time. You can't pass them as props from outside the component, or use the results of function calls, for example.
71+
72+
This does not work:
10073

10174
```js
102-
//Doesn't work
75+
// ⚠️ Doesn't work
76+
10377
({ logo }) => <Img src={logo}>
10478
```
10579

10680
...and nor does this:
10781

10882
```js
109-
//Doesn't work
83+
// ⚠️ Doesn't work
84+
11085
() => {
11186
const width = getTheWidthFromSomewhere();
11287
return <Img src="trex.png" width={width}>
@@ -134,42 +109,22 @@ const width = 300
134109
}
135110
```
136111

137-
## Installation
138-
139-
```bash
140-
npm install gatsby-plugin-image gatsby-plugin-sharp
141-
```
142-
143-
...then add it to your `gatsby-config.js`:
144-
145-
```js
146-
module.exports = {
147-
//...
148-
plugins: [
149-
"gatsby-plugin-sharp",
150-
"gatsby-plugin-image",
151-
//...
152-
],
153-
}
154-
```
155-
156112
### API
157113

158-
The only required prop is `src`. The default type is `fixed`. The other props match those of [the new GatsbyImage component](#gatsby-image-next-generation)
114+
The only required prop is `src`. The default type is `fixed`. The other props match those of [the new GatsbyImage component](#gatsbyimage). You can also pass in options which are forwarded to [`gatsbyImageData`](#graphql-resolver).
159115

160-
## gatsby-image next generation
116+
## GatsbyImage
161117

162118
Speedy, optimized images without the work.
163119

164-
gatsby-image is a React component specially designed to give your users a great image experience. It combines speed and best practices. You can use any image processing library that you want. We suggest using gatsby-plugin-sharp as your image processor. Saving images locally improves [the important health metrics](https://web.dev/vitals/) for your site.
120+
GatsbyImage is a React component specially designed to give your users a great image experience. It combines speed and best practices.
165121

166-
Note: gatsby-image is not a drop-in replacement for <img />. It's optimized for fixed width/height images and images that stretch the full-width of a container. You can build your own Gatsby-Image with the utilities we export from this package.
122+
Note: GatsbyImage is not a drop-in replacement for `<img>`. It's optimized for fixed width/height images and images that stretch the full-width of a container. You can build your own GatsbyImage with the utilities we export from this package.
167123

168124
## Table of Contents
169125

170126
- [Problem](#problem)
171127
- [Solution](#solution)
172-
- [Install](#install)
173128
- [How to use](#how-to-use)
174129
- [Types of Responsive Images](#three-types-of-responsive-images)
175130
- [Gatsby Image Props](#gatsby-plugin-image-props)
@@ -208,34 +163,14 @@ With Gatsby, we can make images way _way_ better.
208163
processing capabilities powered by GraphQL and Sharp. To produce perfect images,
209164
you need only:
210165

211-
1. Import `{ GatsbyImage } from "gatsby-plugin-image"` and use it in place of the built-in `img`.
166+
1. Import `{ GatsbyImage } from "gatsby-plugin-image"`.
212167
2. Write a GraphQL query with all necessary fields needed by `gatsby-plugin-image`.
213168

214169
The GraphQL query creates multiple thumbnails with optimized JPEG and PNG
215170
compression. The `gatsby-plugin-image` component automatically sets up the "blur-up"
216171
effect as well as lazy loading of images further down the screen.
217172

218-
## Install
219-
220-
`npm install gatsby-plugin-image`
221-
222-
Depending on the gatsby starter you used, you may need to include [gatsby-transformer-sharp](/packages/gatsby-transformer-sharp/) and [gatsby-plugin-sharp](/packages/gatsby-plugin-sharp/) as well, and make sure they are installed and included in your gatsby-config.
223-
224-
```shell
225-
npm install gatsby-transformer-sharp gatsby-plugin-sharp
226-
```
227-
228-
Then in your `gatsby-config.js`:
229-
230-
```js
231-
plugins: [
232-
`gatsby-transformer-sharp`,
233-
`gatsby-plugin-sharp`,
234-
`gatsby-plugin-image`,
235-
]
236-
```
237-
238-
Also, make sure you have set up a source plugin, so your images are available in GraphQL queries. For example, if your images live in a project folder on the local filesystem, you would set up `gatsby-source-filesystem` in `gatsby-config.js` like so:
173+
Make sure you have set up a source plugin, so your images are available in GraphQL queries. For example, if your images live in a project folder on the local filesystem, you would set up `gatsby-source-filesystem` in `gatsby-config.js` like so:
239174

240175
```js
241176
const path = require(`path`)
@@ -267,12 +202,12 @@ import { GatsbyImage, getImage } from "gatsby-plugin-image"
267202

268203
export default ({ data }) => {
269204
// You can use the helper function `getImage`, which is equivalent to:
270-
// const imageData = data.file.childImageSharp.gatsbyImage.imageData
205+
// const imageData = data.file.childImageSharp.gatsbyImageData
271206
const imageData = getImage(data.file)
272207

273208
return (
274209
<div>
275-
<h1>Hello gatsby-image</h1>
210+
<h1>Hello GatsbyImage</h1>
276211
<GatsbyImage image={imageData} alt="my gatsby image" />
277212
</div>
278213
)
@@ -282,8 +217,6 @@ export const query = graphql`
282217
query {
283218
file(relativePath: { eq: "blog/avatars/kyle-mathews.jpeg" }) {
284219
childImageSharp {
285-
# Specify the image processing specifications right in the query.
286-
# Makes it trivial to update as your page's design changes.
287220
gatsbyImageData(layout: FIXED, width: 125, height: 125)
288221
}
289222
}
@@ -354,44 +287,42 @@ In Gatsby's GraphQL implementation, you specify the type of image with the `layo
354287

355288
# GraphQL resolver
356289

357-
We have added a new resolver to the `ImageSharp` node, with a single field `imageData`. Unlike the existing `fixed` and `fluid` resolvers, this returns a
290+
We have added a new `gatsbyImageData` resolver to the `ImageSharp` node. Unlike the existing `fixed` and `fluid` resolvers, this returns a
358291
JSON type, meaning you don't specify the individual fields, but are instead given the whole object. This is because the object is then passed in to the `<GatsbyImage>` component. The API is like this:
359292

360293
```graphql
361294
coverImage: file(relativePath: { eq: "plant.jpg" }) {
362295
childImageSharp {
363-
gatsbyImage(maxWidth: 720, layout: FLUID, placeholder: TRACED_SVG) {
364-
imageData
365-
}
296+
gatsbyImageData(maxWidth: 720, layout: FLUID, placeholder: TRACED_SVG)
366297
}
367298
}
368299
```
369300

301+
You then use the data like this:
302+
370303
```jsx
371304
import { GatsbyImage, getImage } from "gatsby-plugin-image"
372305

373306
export function Plant({ data }) {
374307
const imageData = getImage(data.coverImage)
375-
return <GatsbyImage image={imageData} />
308+
return <GatsbyImage image={imageData} alt="Plant" />
376309
}
377310
```
378311

379-
The helper function `getImage` takes a file node and returns `file?.childImageSharp?.gatsbyImage?.imageData`
312+
The optional helper function `getImage` takes a file node and returns `file?.childImageSharp?.gatsbyImageData`
380313

381314
Because this no longer uses fragments to specify which fields to return, it instead uses arguments passed to the resolver. These include:
382315

383316
- `placeholder`: Format of generated placeholder image.
384-
DOMINANT*COLOR: a solid color, calculated from the dominant color of the image. (default) \_Currently disabled until sharp is updated*
385-
BLURRED: a blurred, low resolution image, encoded as a base64 data URI
386-
TRACED_SVG: a low-resolution traced SVG of the image.
387-
NONE: no placeholder. Set "background" to use a fixed background color.
317+
- `BLURRED`: (default) a blurred, low resolution image, encoded as a base64 data URI
318+
- `TRACED_SVG`: a low-resolution traced SVG of the image.
319+
- `NONE`: no placeholder. Set "background" to use a fixed background color.
320+
- `DOMINANT_COLOR`: a solid color, calculated from the dominant color of the image. _Currently disabled until sharp is updated_
388321
- `layout`: The layout for the image.
389-
FIXED: A static image sized, that does not resize according to the screen width
390-
FLUID: The image resizes to fit its container. Pass a "sizes" option if it isn't going to be the full width of the screen.
391-
CONSTRAINED: Resizes to fit its container, up to a maximum width, at which point it will remain fixed in size.
392-
- `outputPixelDensities`: A list of image pixel densities to generate, for high-resolution (retina) screens. It will never generate images larger than the source, and will always a 1x image.
393-
Default is [ 0.25, 0.5, 1, 2 ], for fluid/constrained images, and [ 1, 2 ] for fixed. In this case, an image with a fluid layout and maxWidth = 400 would generate images at 100, 200, 400 and 800px wide
394-
395-
- `sizes`: The "sizes" property, passed to the img tag. This describes the display size of the image.
396-
This does not affect the generated images, but is used by the browser to decide which images to download. You can leave this blank for fixed images, or if the responsive image
397-
container will be the full width of the screen. In these cases we will generate an appropriate value.
322+
- `FIXED:` A static image sized, that does not resize according to the screen width
323+
- `FLUID`: The image resizes to fit its container. Pass a "sizes" option if it isn't going to be the full width of the screen.
324+
- `CONSTRAINED`: Resizes to fit its container, up to a maximum width, at which point it will remain fixed in size.
325+
- `outputPixelDensities`: A list of image pixel densities to generate, for high-resolution (retina) screens. It will never generate images larger than the source, and will always include a 1x image.
326+
Default is `[ 0.25, 0.5, 1, 2 ]`, for fluid/constrained images, and `[ 1, 2 ]` for fixed. In this case, an image with a fluid layout and maxWidth = 400 would generate images at 100, 200, 400 and 800px wide
327+
- `sizes`: The "[sizes](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images)" attribute, passed to the `<img>` tag. This describes the display size of the image. This does not affect the generated images, but is used by the browser to decide which images to download. You can leave this blank for fixed images, or if the responsive image container will be the full width of the screen. In these cases we will generate an appropriate value. If, however, you are generating responsive images that are not the full width of the screen, you should provide a sizes property for best performance.
328+
- `formats`: an array of file formats to generate. The default is `[AUTO, WEBP]`, which means it will generate images in the same format as the source image, as well as in the next-generation [WebP](https://developers.google.com/speed/webp) format. We strongly recommend you do not change this option, as doing so will affect performance scores.

0 commit comments

Comments
 (0)