{"id":16492417,"url":"https://github.com/coreyward/gatsby-plugin-sanity-image","last_synced_at":"2025-04-05T11:11:06.432Z","repository":{"id":37534234,"uuid":"308954795","full_name":"coreyward/gatsby-plugin-sanity-image","owner":"coreyward","description":"Gatsby plugin providing easy responsive behavior for Sanity-hosted images","archived":false,"fork":false,"pushed_at":"2025-03-06T00:39:24.000Z","size":279,"stargazers_count":39,"open_issues_count":0,"forks_count":13,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-03-29T10:08:58.624Z","etag":null,"topics":["gatsby","gatsby-plugin","gatsbyjs","image","react","sanity","sanity-io"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/coreyward.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-10-31T19:12:53.000Z","updated_at":"2024-12-12T16:55:40.000Z","dependencies_parsed_at":"2024-06-18T20:06:00.514Z","dependency_job_id":"4fe08e24-7aee-438d-ac99-6635779d1ab2","html_url":"https://github.com/coreyward/gatsby-plugin-sanity-image","commit_stats":{"total_commits":88,"total_committers":7,"mean_commits":"12.571428571428571","dds":"0.44318181818181823","last_synced_commit":"c6bad767882ca00c830a9edf93d19c600c68fb98"},"previous_names":[],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyward%2Fgatsby-plugin-sanity-image","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyward%2Fgatsby-plugin-sanity-image/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyward%2Fgatsby-plugin-sanity-image/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyward%2Fgatsby-plugin-sanity-image/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/coreyward","download_url":"https://codeload.github.com/coreyward/gatsby-plugin-sanity-image/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247325693,"owners_count":20920714,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["gatsby","gatsby-plugin","gatsbyjs","image","react","sanity","sanity-io"],"created_at":"2024-10-11T14:05:47.016Z","updated_at":"2025-04-05T11:11:06.404Z","avatar_url":"https://github.com/coreyward.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# gatsby-plugin-sanity-image\n\n[![Latest version](https://img.shields.io/npm/v/gatsby-plugin-sanity-image?label=version\u0026color=brightGreen\u0026logo=npm)](https://www.npmjs.com/package/gatsby-plugin-sanity-image)\n![Dependency status](https://img.shields.io/librariesio/release/npm/gatsby-plugin-sanity-image)\n[![Open issues](https://img.shields.io/github/issues/coreyward/gatsby-plugin-sanity-image)](https://github.com/coreyward/gatsby-plugin-sanity-image/issues)\n![Gatsby version compatibility](https://img.shields.io/badge/dynamic/json?color=blueviolet\u0026label=gatsby%20versions\u0026query=peerDependencies.gatsby\u0026url=https%3A%2F%2Fraw.githubusercontent.com%2Fcoreyward%2Fgatsby-plugin-sanity-image%2Fmaster%2Fpackage.json)\n\nThe well-considered marriage between Sanity’s image assets and Gatsby you’ve\nbeen looking for.\n\n- Outputs a single `\u003cimg\u003e` tag, no nested DOM structure to mess with\n- Supports low-quality image previews out of the box, without build-time\n  penalties (native lazy loading)\n- Generates a `srcSet` automatically based on the `width` you specify _in your\n  component code_ (meaning you can change it on the fly!)\n- Applies Sanity hotspot data as the `object-position` in case you need it\n- Computes cropped dimensions and drops `srcSet` entries that are larger than\n  the source dimensions when appropriate (follows Sanity’s image-url parameters)\n- Configure image quality, resizing behavior, file format, and more with\n  [Sanity’s Image API](https://www.sanity.io/docs/image-urls)\n\n## At a Glance\n\nYou can find the full writeup on getting going below, but in the interest of\nmaking it easy to see if this is the thing you are looking for, here’s what\nusing it looks like:\n\n```jsx\nimport Image from \"gatsby-plugin-sanity-image\"\n\nconst YourSweetComponent = ({ image }) =\u003e (\n  \u003cImage\n    // pass asset, hotspot, and crop fields\n    {...image}\n    // tell Sanity how large to make the image (does not set any CSS)\n    width={500}\n    // style it how you want it\n    style={{\n      width: \"100%\",\n      height: \"100%\",\n      objectFit: \"cover\",\n    }}\n  /\u003e\n)\n\nexport default YourSweetComponent\n\nexport const query = graphql`\n  {\n    sanityDocumentOfSomeKind {\n      sweetImage {\n        ...ImageWithPreview\n      }\n    }\n  }\n`\n```\n\nThat’s the gist, folks. Read on for the full scoop!\n\n## Getting Started\n\n### Install it\n\n```sh\nyarn add gatsby-plugin-sanity-image\n```\n\n### Configure it\n\n\u003e ℹ️ **Note**: If this is your first time adding a Gatsby plugin, be sure to\n\u003e [read this guide first](https://www.gatsbyjs.com/docs/using-a-plugin-in-your-site/)—the\n\u003e below is a shorthand notation.\n\nSimple configuration:\n\n```js\n{\n  resolve: \"gatsby-plugin-sanity-image\",\n  options: {\n    // Sanity project info (required)\n    projectId: \"abcd1234\",\n    dataset: \"production\",\n  },\n}\n```\n\nIf you have custom image types in Sanity (e.g. `mainImage` that is of type\n`image`) you’ll need to add one more option before you move on. Check the full\nexample or the [Configuration Directives](#configuration-directives) below.\n\n\u003cdetails\u003e\n  \u003csummary\u003eExpand the full configuration example\u003c/summary\u003e\n\n```js\n// Full configuration:\n{\n  resolve: \"gatsby-plugin-sanity-image\",\n  options: {\n    // Sanity project info (required)\n    projectId: \"abcd1234\",\n    dataset: \"production\",\n\n    // Custom image types are also supported. For example, if you have a\n    // `mainImage` type in Sanity, it winds up in Gatsby as `SanityMainImage`,\n    // and so you would add \"SanityMainImage\" to the customImageTypes array.\n    customImageTypes: [],\n\n    // This config directive allows you to specify the field that should be\n    // retrieved and used as alt text when no `alt` prop is passed to the image\n    // component. See docs for more detail.\n    altFieldName: \"alt\",\n\n    // SanityImage will warn you if you do not set an alt prop/attribute. If\n    // you don't want this behavior, you can disable this here. By default this\n    // is only enabled in development.\n    warnOnMissingAlt: process.env.NODE_ENV === \"development\",\n\n    // When no `alt` prop is available, SanityImage can default to setting an\n    // empty string value. This can prevent accessibility audits from detecting\n    // images that should have an alt value, but enabling it allows you to only\n    // set alt text when it is needed.\n    emptyAltFallback: false,\n\n    // Additional params to pass to @sanity/image-url for every image. The\n    // default is shown here, so you can omit the directive if you are happy\n    // with what you see here.\n    defaultImageConfig: {\n      quality: 75,\n      fit: \"max\",\n      auto: \"format\",\n    },\n\n    // ########################################################################\n    // Configuration directives below this point are rarely needed. If you    #\n    // aren't confident you need them, you probably do not need them.         #\n    // ########################################################################\n\n    // If you prefer a different fragment name, such as `MagicImage`, enter it\n    // here. This needs to be unique amongst your GraphQL types. `WithPreview`\n    // will be appended for the second fragment (e.g. MagicImageWithPreview).\n    fragmentName: \"Image\",\n\n    // By default, image fields are typed as SanityImage, but there are cases\n    // where you might want to use a custom schema or where custom image types\n    // are not under the SanityImage type. In this case, you\n    // can alter the type that the fragment is defined\n    // on here without redefining the fragments.\n    fragmentTypeName: \"SanityImage\",\n\n    // If you prefer to retreive data another way or if you want to define the\n    // fragment you use separately, you can opt-out of having fragments included\n    // entirely.\n    includeFragments: true,\n  },\n}\n```\n\n\u003c/details\u003e\n\nDon’t forget to restart `gatsby develop` after you update your\n`gatsby-config.js`!\n\n## Usage\n\n1. Query for the image fields\n2. Pass the retrieved fields as props to the `SanityImage` component\n3. Use it like normal—it's just an `img` tag! 🤯😇\n\n### Querying for image data via GraphQL\n\nThis plugin includes two GraphQL fragments that will fetch the fields needed for\ndisplay from any Sanity image asset. You do not have to use them, but they are\nconvenient and help keep you away from confusing bugs.\n\nIn most cases, you'll want to use the `ImageWithPreview` fragment:\n\n```graphql\nexport const query = graphql`\n  {\n    sanitySomeDocument {\n      yourImageField {\n        ...ImageWithPreview\n      }\n    }\n  }\n`\n```\n\nThis will retrieve the `asset`, `hotspot`, and `crop` fields and includes a\nlow-quality image preview that will be shown while the full image is loading.\n\n#### Opting out of blurry preview images\n\nIf you have an image that you do NOT want to use the preview image for, you can\nopt to use the simpler `Image` fragment instead. This has all of the same fields\nwith the exception of the preview. This will keep your HTML files a bit lighter,\nbut you may wind up with more cumulative layout shift as the browser fetches the\nimage dimensions and evaluates your styles.\n\nNote: If you are using an SVG image, you probably do _not_ want to fetch the\npreview since it’ll get thrown away—the `SanityImage` component aborts early on\nSVG images to avoid generating meaningless `srcSet` data that reduces cache\nefficiency.\n\n### Using the `SanityImage` component\n\nThe data you fetched from GraphQL should be an object that you can expand\nstraight into the `SanityImage` component and just work. If you used the\n`ImageWithPreview` fragment, `SanityImage` will do the right thing\nautomatically.\n\n```jsx\nimport SanityImage from \"gatsby-plugin-sanity-image\"\n\nconst YourComponent = ({ yourImageFieldData }) =\u003e\n  \u003cSanityImage {...yourImageFieldData} width={300} alt=\"Sweet Christmas!\"\u003e\n```\n\n\u003cdetails\u003e\n  \u003csummary\u003eThis renders an image tag like this:\u003c/summary\u003e\n\n```html\n\u003c!--\n  Using {baseUrl} below to refer to a string with this format:\n  https://cdn.sanity.io/images/{projectId}/{dataset}/{imageId}?w=300\u0026amp;h=600\u0026amp;q=75\u0026amp;fit=max\u0026amp;auto=format\n--\u003e\n\u003cimg\n  src=\"{baseUrl}\"\n  srcset=\"\n    {baseUrl}\u0026amp;dpr=0.5  150w,\n    {baseUrl}\u0026amp;dpr=0.75 225w,\n    {baseUrl}\u0026amp;dpr=1    300w,\n    {baseUrl}\u0026amp;dpr=1.5  450w,\n    {baseUrl}\u0026amp;dpr=2    600w\n  \"\n  loading=\"lazy\"\n  alt=\"Sweet Christmas!\"\n  class=\"css-1jku2jm-SanityImage\"\n/\u003e\n```\n\n\u003c/details\u003e\n\nNote that `SanityImage` is not doing anything to style your image based on the\nwidth or height you provide (aside from setting a class with `object-position`\nset, should you choose to use it). In practice, it's rare that these values\nalign consistently with a particular layout, and library control of this makes\nit difficult to predict the output given a particular input.\n\nInstead you can style the resulting `img` tag just like any other element.\n`SanityImage` will pass through `className` and `style` props, and it makes no\nassumptions about your image presentation.\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003cstrong\u003e⚠️ Minor gotchas with deferred loading\u003c/strong\u003e\u003c/summary\u003e\n\n`SanityImage` is relying on browser-native deferred image loading. This\ngenerally works fine in browsers that support it, but there are situations where\nthe unloaded image is hidden or covered, resulting in the full image never\nloading.\n\nIf this happens, you can override the styles set on the full-size image using\nthe `img[data-loading]` selector. This image sits immediately adjacent to the\nspaceball image and has the following default styles _while loading_:\n\n```css\nposition: absolute;\nwidth: 10px !important; /* must be \u003e 4px to be lazy loaded */\nheight: 10px !important; /* must be \u003e 4px to be lazy loaded */\nopacity: 0;\nzindex: -10;\npointerevents: none;\nuserselect: none;\n```\n\n\u003c/details\u003e\n\n## Component Props\n\nFor convenience, `__typename`, `_type`, and `_key` props will be ignored. Other\nprops will be passed through to the final `img` element (e.g. native HTML\nattributes).\n\n\u003csub\u003e\\*️⃣ = Required\u003c/sub\u003e\n\n| Prop        | Type   | Description                                                                                                                                                                                                |\n| ----------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `asset` \\*️⃣ | Object | The `asset` object fetched from GraphQL. Should have an `_id` property on it, and possibly `metadata` (if you're using low-quality image previews).                                                        |\n| `crop`      | Object | The `crop` values fetched from GraphQL (`top`, `right`, `bottom`, and `left`)                                                                                                                              |\n| `hotspot`   | Object | The `hotspot` values fetched from GraphQL (`width`, `height`, `x`, and `y`)                                                                                                                                |\n| `width` \\*️⃣ | Number | This will be used as a target value to generate a `srcSet` of images both smaller and larger.                                                                                                              |\n| `height`    | Number | Used to further constrain the image. Note: due to [a bug in the `@sanity/image-url` library](https://github.com/sanity-io/image-url/issues/32), setting this will cause `fit` modes to be largely ignored. |\n| `config`    | Object | Parameters for `@sanity/image-url`. [Full list here](https://www.sanity.io/docs/image-url).                                                                                                                |\n| `options`   | Object | See below.                                                                                                                                                                                                 |\n\n### Options\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003ccode\u003e__experimentalAspectRatio\u003c/code\u003e (Boolean)\u003c/summary\u003e\n\nIf enabled, `SanityImage` will attempt to compute the final aspect ratio and use\nit to set `width` and `height` attributes on both the low-quality preview image\nas well as the final image. This does not currently take into account any\n`config` options, including `fit` modes or transforming options like `rect` or\n`orientation`.\n\n\u003c/details\u003e\n\n## Configuration Directives\n\n\u003csub\u003e\\*️⃣ = Required\u003c/sub\u003e\n\n| Option                        | Type    | Default         | Description                                                                                                                                                                                                                                                                                                                                                                               |\n| ----------------------------- | ------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `projectId` \\*️⃣               | String  |                 | Sanity Project ID                                                                                                                                                                                                                                                                                                                                                                         |\n| `dataset` \\*️⃣                 | String  |                 | Sanity Dataset ID                                                                                                                                                                                                                                                                                                                                                                         |\n| `customImageTypes`            | Array   | `[]`            | If you would like to use the `Image` and `ImageWithPreview` fragments on custom image types, specify all custom type names in the `customImageTypes` array. For more detail, [follow this guide](https://github.com/coreyward/gatsby-plugin-sanity-image/wiki/Custom-Sanity-Image-Types).                                                                                                 |\n| `altFieldName`                | String  | `null`          | If you are adding alt text directly to image assets in your Sanity Studio (e.g. via a plugin like [sanity-plugin-media](https://github.com/robinpyon/sanity-plugin-media/)), this plugin can include that field in the `Image` and `ImageWithPreview` fragments and utilize it as the default/fallback `alt` attribute value when no `alt` prop is passed to the `SanityImage` component. |\n| `warnOnMissingAlt`            | Boolean | See note 👉     | SanityImage will warn you if you do not set an alt prop/attribute. If you don't want this behavior, you can disable this here. By default this is only enabled in development.                                                                                                                                                                                                            |\n| `emptyAltFallback`            | Boolean | `false`         | When no `alt` prop is available, SanityImage can default to setting an empty string value. This can prevent accessibility audits from detecting images that should have an alt value, but enabling it allows you to only set alt text when it is needed.                                                                                                                                  |\n| `defaultImageConfig`          | Object  | See below.      | Additional params to pass to the Sanity image URL builder. These will be converted into function calls against `@sanity/image-url`. [Here is the full list of methods available](https://www.sanity.io/docs/image-url).                                                                                                                                                                   |\n| **Less common directives** ⬇️ |         |                 |  It is unlikely you will need to use these. Proceed with caution.                                                                                                                                                                                                                                                                                                                         |\n| `fragmentName`                | String  | `\"Image\"`       | If you prefer a different fragment name, such as `MagicImage`, enter it here. This needs to be unique amongst your GraphQL types. `WithPreview` will be appended for the second fragment (e.g. MagicImageWithPreview).                                                                                                                                                                    |\n| `fragmentTypeName`            | String  | `\"SanityImage\"` | By default, image fields are typed as SanityImage, but there are cases where you might want to use a custom schema or where custom image types are not under the `SanityImage` type. In this case, you can alter the type that the fragment is defined on without redefining the fragments.                                                                                               |\n| `includeFragments`            | Boolean | `true`          | If you prefer to retreive data another way or if you want to define the fragment you use separately, you can opt-out of having fragments included entirely.                                                                                                                                                                                                                               |\n\nThe default value for `defaultImageConfig` is as follows:\n\n```js\n{\n  quality: 75,   // use reasonable lossy compression level\n  fit: \"max\",    // like `object-fit: contain`, but never scaling up\n  auto: \"format\" // automatically select next-gen image formats on supporting browsers\n}\n```\n\n## More things to know\n\n- If you don't specify `width` the uploaded image width is used.\n- You are encouraged to use the `sizes` attribute to steer browsers to select\n  the most appropriate image from the `srcSet` based on the viewport width\n- You can target the low-quality image preview element via `img[data-lqip]`\n  should you want to style it differently\n\n## License\n\nCopyright ©2022 Corey Ward. Available under the\n[MIT License](https://github.com/coreyward/gatsby-plugin-sanity-image/blob/master/LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoreyward%2Fgatsby-plugin-sanity-image","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcoreyward%2Fgatsby-plugin-sanity-image","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoreyward%2Fgatsby-plugin-sanity-image/lists"}