Movatterモバイル変換


[0]ホーム

URL:


Migrate to Netlify Today

Netlify announces the next evolution of Gatsby Cloud.Learn more

SupportLog In

Introduction

Gatsby has best-in-class image support with itsgatsby-plugin-image feature. With it you can easily add responsive, optimized images to sites in all modern formats. Traditionally, images were downloaded and transformed to enable this behavior. Image CDN solves this by skipping image processing during the build, and instead deferring and offloading it to a dedicated image CDN. Visitors still get images in the most optimized formats such as AVIF and WebP, but site builds complete in a fraction of the time.

By the end of this part of the tutorial, you will be able to:

  • Add Image CDN support to your source plugin
  • Use Image CDN withgatsby-plugin-image in your example site

Add Image CDN to your plugin

Gatsby’s Image CDN feature can be added to any Gatsby source plugin. We recommend using it over manual file downloading for the reasons above. As long as your API gives back a URL to an image, you should be able to implement the required code. Basically, for Image CDN to work you need two things:

  • A GraphQL root node type that implements theRemoteFile interface
  • During node creation for that GraphQL node type, certain fields must exist on the node to match whatRemoteFile expects

InPart 3 you learned that root node types need to implement theNode interface. Similarly toNode,RemoteFile is also provided by Gatsby itself and will handle all the complicated pieces of Image CDN behind the scenes.

Pro tip: Gatsby’s Image CDN feature is smart enough to work on all platforms, even if no CDN provider like on Gatsby Cloud or Netlify is available. In those cases (including locally on your computer) it automatically falls back to processing images during the build. This won’t give users a build improvement but things on the frontend will still behave the same and builds won’t fail.

TheRemoteFile interface has the following shape:

For node types implementingRemoteFile this means:

  • Always required arepublicUrl (the url to the image/file),mimeType (e.g.image/jpg orapplication/pdf), andfilename.publicUrl will be defined throughurl during node creation.
  • width,height,resize, andgatsbyImage can be null. This is because theRemoteFile interface can also handle assets other than images, like PDFs.

For node types that are images this means:publicUrl,mimeType,filename,width, andheight are mandatory.

Pro tip:resize andgatsbyImage will be provided by Gatsby. They are GraphQL resolvers relying on the existing data on the GraphQL node. You’ll usegatsbyImage later to get your data for the<GatsbyImage /> comopnent.

Here’s an example of a GraphQL root node that implementsRemoteFile and creates nodes with all required fields for images:

  • Schema customization to implementRemoteFile onImageAsset:

  • Creating theImageAsset node with all required fields:

As you can see theImageAsset node holds all required fields but you can also add your own additional, arbitrary fields (likealt shown in the example). OnceImageAsset is created, you’ll be able to callgatsbyImage andresize on these GraphQL nodes and use Image CDN.

The URL you provide to theurl field should link to the image version with the highest resolution, so if e.g. your API can provide image URLs in different sizes, pick the one with the best resolution.

One field that hasn’t been mentioned yet is theplaceholderUrl. The<GatsbyImage /> component supports displaying a placeholder while the image loads. You can tell Image CDN to use yourplaceholderUrl to generate said placeholder. If your API supports returning different sized images through URL segments or URL params, you can place%width% and%height% into the URL. This tutorial uses Unsplash as it supportsdynamically resizing images and thus both are used with thew query param. Alternatively, you could also provide the smallest possible image available from your API to this field.

Are width and height missing from the API response? Not every API returns width, height, and mimeType for an image. You can useprobe-image-size to get these information from your remote URL.

probe-image-size example

probe-image-size returns a Promise so you’ll need toawait its result. You could use it something like this:

Task: WritecreateAssetNode utility

Time to apply your theoretical knowledge about Image CDN to your own plugin.

You’ll create a new root node calledAsset through acreateAssetNode utility. You can think of it as a more specialized version of thenodeBuilder utility, only responsible for creating nodes that should becomeAsset and hence Image CDN capable. Creating a separateAsset type will also make schema customization in the next task easier.

  1. Openplugin/src/constants.ts and add a new node type:

  2. Openplugin/src/source-nodes.ts. Add the type imports forIRemoteImageNodeInput andIPostImageInput, create a shell forcreateAssetNode at the end of the file:

    Similar tonodeBuilder it receivesgatsbyApi to call the various node helpers butdata must be in the shape ofIPostImageInput. This TypeScript type is identical to theimage object shape inside each post inapi/src/data.ts.

  3. Create the function body forcreateAssetNode by following whatnodeBuilder is doing:

    TypeScript should complain about missing fields onasstNode:

    These are exactly the fields that are required for image assets.

  4. Add the missing fields to the node:

    And that’s it, you can createAsset nodes now! In the next task you’ll actually usecreateAssetNode.

Task: Apply schema customizations

So far yourcreateAssetNode utility isn’t doing anything. You’ll need to use it inside thenodeBuilder utility to add an additionalimage field toPost nodes. However, this will only work once you have successfully implemented the second requirement of Image CDN: ThatAsset implements theRemoteFile interface.

A lot of this task builds upon your knowledge fromPart 3, specifically theforeign-key relationship section. Feel free to revisit those sections if you need a refresher.

You’ll implement theRemoteFile interface forAsset and make it a root node. Then you’ll create a foreign-key relationship betweenAsset and theimage field onPost.

  1. Openplugin/src/create-schema-customization.ts. Change the name ofPostImage toAsset and implement bothNode andRemoteFile for it:

    Nodes thatcreateAssetNode creates will be GraphQL root nodes now.

    Type builder example

    If you’re not using the SDL syntax but type builders, you’d add it like this:

  2. Create a foreign-key relationship betweenPost andAsset through@link on theimage field.

    If you remember from Part 3, the default behavior of@link is to use theid from the target node. Keep that in mind for the following instructions.

  3. Open theplugin/src/source-nodes.ts file and add a return statement to thecreateAssetNode function. Return the generatedid:

  4. A node of typePost should have the generatedid ofAsset as itsimage field. Because only posts can have images, you can conditionally add data to the node if certain conditions are met like this:

  5. Thesome-id string should be replaced by theAsset id of course. SincecreateAssetNode returns theid, you can use its result:

  6. Restart thedevelop:site script and open GraphiQL athttp://localhost:8000/___graphql. Run the following query:

    You should get a result back like this:

    It works! Note:<long-string> is added above to make things easier to read. If you’re seeing an error, stop thedevelop:site script, runyarn clean:site and retryyarn develop:site again.

    In the next task you’ll be able to use the result fromgatsbyImage inside your pages.

Use Image CDN in your site

When usinggatsby-plugin-image you use thegatsbyImageData GraphQL field to access the necessary data. With Image CDN this name changes togatsbyImage — you’ve learned this in the last task. The only relevant difference betweengatsbyImageData andgatsbyImage is that the latter requires awidth orheight argument.

Refer to thegatsby-plugin-image how-to for instructions on its usage as this tutorial won’t go into details about that.

Task: Update individual post pages

  1. Opensite/src/pages/{Post.slug}.tsx and addimage to the GraphQL query:

  2. Import the necessarygatsby-plugin-image helpers and components and use them withimage:

  3. Go tohttp://localhost:8000/post-1/. You should see a dog image on the page:

    A screenshot of "http://localhost:8000/post-1/" in a web browser. The individual post page for "The first post" is shown, together with a corgi dog looking at the camera. The dog is smiling.

Summary

Magnificent! Your posts now have photos of cute dogs.

Take a moment to think back on what you’ve learned so far. Challenge yourself to answer the following questions from memory:

  • What are the two steps required to implement Image CDN in a source plugin?
  • What types of files canRemoteFile support?
  • What are the mandatory fields thatRemoteFile expects?

Key takeaways

  • By using Image CDN you can offload the heavy image generation to dedicated providers, giving users of your source plugin great build performance.
  • GraphQL root node types of your plugin that represent files and/or images should implement theRemoteFile interface and have all required fields on their node.
  • You can usegatsbyImage in your GraphQL result together withgatsby-plugin-image like you’re used to.

Share Your Feedback!

Our goal is for this tutorial to be helpful and easy to follow. We’d love to hear your feedback about what you liked or didn’t like about this part of the tutorial.

Use the “Was this doc helpful to you?” form at the bottom of this page to let us know what worked well and what we can improve.

What’s coming next?

In Part 7 advanced topics like Content Sync, testing, debugging, and more will be explained.

Continue to Part 7

Start building today on Netlify!

Gatsby is powered by the amazing Gatsby
community and Gatsby, the company.


[8]ページ先頭

©2009-2025 Movatter.jp