Code Monkey home page Code Monkey logo

gatsby's Introduction

imgix logo

@imgix/gatsby is a multi-faceted plugin to help the developer use imgix with Gatsby.

npm version Downloads Build Status License FOSSA Status styled with prettier All Contributors


Overview / Resources

Before you get started with this library, it's highly recommended that you read Eric Portis' seminal article on srcset and sizes. This article explains the history of responsive images in responsive design, why they're necessary, and how all these technologies work together to save bandwidth and provide a better experience for users. The primary goal of this library is to make these tools easier for developers to implement, so having an understanding of how they work will significantly improve your experience with this library.

Below are some other articles that help explain responsive imagery, and how it can work alongside imgix:

Why use imgix instead of gatsby-transform-sharp?

Integrating imgix with Gatsby provides a few key advantages over the core image experience in Gatsby:

  1. Far-reduced build time and better developer experience. Since we offload the image rendering to our cloud, we free up your machine from doing complex image transformations, meaning your builds are as snappy as they can be.
  2. Access to imgix's suite of transformations and optimizations. imgix has a larger variety of image transformations than are possible with the built in Gatsby system. Furthermore, we are continuously improving our image optimization to push the boundaries of image performance.
  3. Better image responsiveness on the page. As we are able to create far more derivative images at different resolutions due to our cloud rendering stack, we can offer an image closer to the source resolution of your users' browsers, meaning faster load times and less bandwidth usage for your users (and you!).
  4. Access to imgix's best-in-class CDN. imgix has invested significant time and effort into a world-leading CDN, which ensures images are delivered your website's customers as quick as possible.
  5. Faster time-to-awesome. imgix offers a set of default optimizations which allow you to achieve outstanding image quality which still keeping image size small, and allows you to focus on other aspects of your website.

Get started

Firstly, this library requires an imgix account, so please follow this quick start guide if you don't have an account.

Then, install this library with the following commands, depending on your package manager.

  • NPM: npm install @imgix/gatsby
  • Yarn: yarn add @imgix/gatsby

Finally, check out the section in the usage guide below that most suits your needs.

Usage

What section should I read?

To find what part of this usage guide you should read, select the use case below that best matches your use case:

GraphQL transform API

This feature can be best thought of as a replacement for gatsby-image-sharp, for imagesย that are provided by Gatsby Source plugins, such as Contentful or Prismic. These plugins provide data that is accessed with the Gatsby GraphQL API, with images that are stored on the internet. This plugin can transform those images using imgix, and serve them to your customers.

Configuration

This source must be configured in your gatsby-config file as follows:

// Add to start of file
const { ImgixSourceType } = require('@imgix/gatsby');

module.exports = {
  //...
  plugins: [
    // your other plugins here
    {
      resolve: `@imgix/gatsby`,
      options: {
        // This is the domain of your imgix source, which can be created at
        // https://dashboard.imgix.com/.
        // Required for "Web Proxy" imgix sources.
        domain: 'example.imgix.net',

        // This is the source's secure token. Can be found under the "Security"
        // heading in your source's configuration page, and revealed by tapping
        // "Show Token". Required for web-proxy sources.
        secureURLToken: 'abcABC123',

        // This configures the plugin to work in proxy mode.
        // Can be AmazonS3, GoogleCloudStorage, MicrosoftAzure, or WebFolder.
        sourceType: ImgixSourceType.WebProxy,

        // These are some default imgix parameters to set for each image. It is
        // recommended to have at least this minimal configuration.
        defaultImgixParams: { auto: 'format,compress' },

        // This configures which nodes to modify.
        fields: [
          // Add an object to this array for each node type you want to modify. Follow the instructions below for this.
        ],
      },
    },
  ],
};
Adding a fields item correctly

It's necessary to add a configuration for each GraphQL node type you would like to modify. For example, if you have a page which queries both for blog posts, and also blog post categories, you will need to add items for each type separately.

The first step is to find the node type you would like to modify. To do this, look at the GraphQL query for the image you would like to modify. You need to find the node type for the node that image belongs to. For example, for the following query, the node type is ContentfulAsset, since that is the type of heroImage. This can be confirmed by copying the query into the GraphiQL editor and hovering over the node type. More detailed instructions on how to find the node types can be found in this section

query HomeQuery {
  allContentfulBlogPost {
    nodes {
      heroImage { # this is the node to modify
        fluid {...}
      }
    }
  }

}

Then, you need to configure a field for this node type. The quickest way to configure this is to see if the examples below include a configuration for the node that you would like to transform. If it exists, just copy and paste that into the list of fields, and you're done. Otherwise, skip to the section for manual setup.

gatsby-source-contentful
// ContentfulAsset
{
  nodeType: "ContentfulAsset",
  fieldName: "imgixImage",
  rawURLKey: 'file.url',
  URLPrefix: 'https:',
},
gatsby-source-datocms
{
  nodeType: "DatoCmsAsset",
  rawURLKey: 'entityPayload.attributes.url',
  fieldName: "imgixImage",
},
gatsby-source-drupal
// Drupal
{
  nodeType: 'File',
  rawURLKey: (node) => node.url,
  fieldName: 'imgixImage',
},
Manual config (if your node type doesn't exist above)
{
  // This is the GraphQL node type that you want to modify. There's
  // more info on how to find this below.
  nodeType: '',

  // This is used to pull the raw image URL from the node you want to
  // transform. The value here should be the path in the node that
  // contains the image URL to be transformed.
  // See more information below on how to set this.
  rawURLKey: 'imageUrlKey',

  // This is the name of imgix field that will be added to the type.
  fieldName: 'imgixImage',
},

The rawURLKey value needs to be the path to the raw image URL in the node data that should be transformed.

The steps to setting this value correctly is:

  1. Set the option to:

    rawURLKey: '';
  2. Inspect the logged output. The plugin will try to find a suitable image url in the node's data for you, and if it successfully finds one, it will output the code to replace the function with in the corresponding error message.

    For example, for ContentfulAsset, it will display the following error message:

    Error when resolving URL value for node type Post. This probably means that
    the rawURLKey function in gatsby-config.js is incorrectly set. Please read this
    project's README for detailed instructions on how to set this correctly.
    
    Potential images were found at these paths:
      - imageURL
        Set following configuration options:
          rawURLKey: 'imageURL'
          URLPrefix: 'https:'

    As we can see, the correct value for the options are

    rawURLKey: 'imageURL',
    URLPrefix: 'https:'

    If no value was suggested, you will need to inspect the logged output to find a suitable image URL that corresponds to the image you want to transform. For example, if we're searching ContentfulAsset's data, we see the following output in the console:

    {
      // ...
      file: {
        url: '//images.ctfassets.net/../.jpg',
        details: { size: 7316629, image: [Object] },
        fileName: 'image.jpg',
        contentType: 'image/jpeg'
      },
      // ...
    }

    Therefore, we need to set the option to file.url, to return the url at node.file.url. NB: the value for rawURLKey is passed to lodash.get, so array indices, etc can also be used if necessary.

  3. Set the option to the correct value, making sure that the URL includes an http or https. For this example, since the image URL didn't have a https, we have to add https to the URLPrefix option:

    rawURLKey: 'file.url`,
    URLPrefix: 'https:'
Finding a node's type

The easiest way to find a node's type is to copy the query to the GraphiQL explorer (can be found at localhost:8000/__graphql). Then, while holding Cmd or Ctrl, hover over the node that you are trying to find the type for.

In the screenshot below, we have hovered over the heroImage field, and we can see the type is ContentfulAsset. This is the value we can set in the plugin's config.

hovering over node type to see node type is ContentfulAsset

It's also possible to add __typeName to the GraphQL query to find the node type. This is useful if you are unable to use the GraphiQL explorer. Here we can see again that the node type is ContentfulAsset

node type is again ContentfulAsset

Default imgix parameters

Setting auto: ['format', 'compress'] is highly recommended. This will re-format the image to the format that is best optimized for your browser, such as WebP. It will also reduce unnecessary wasted file size, such as transparency on a non-transparent image. More information about the auto parameter can be found here.

GatsbyImage support

This plugin now supports the latest GatsbyImage component, which delivers better performance and Lighthouse scores, while improving the developer experience.

To use this plugin with GatsbyImage, the usage is quite similar to the normal usage with gatsby-plugin-image. This plugin exposes a gatsbyImageData GraphQL field which is very similar to the native field.

Example:

import gql from 'graphql-tag';
import Img from 'gatsby-image';
import { GatsbyImage } from 'gatsby-plugin-image';

export default ({ data }) => {
  return (
    <GatsbyImage
      image={data.allContentfulAsset.edges[0].node.imgixImage.gatsbyImageData}
    />
  );
};

export const query = gql`
  {
    allContentfulAsset {
      edges {
        node {
          imgixImage {
            gatsbyImageData(width: 400, imgixParams: {})
          }
        }
      }
    }
  }
`;
Shared field params

The layout, width, height, aspectRatio, outputPixelDensities, breakpoints, sizes, and backgroundColor parameters are identical to the parameters offered by the native gatsbyImageData field, and the documentation for those fields can be found in the Gatsby documentation. The other added parameters are specific to imgix and they are documented in the GraphQL type definitions, which can be explored in GraphiQL (usually at http://localhost:8000/__graphiql)

Fluid Images

The following code will render a fluid image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.

import gql from 'graphql-tag';
import Img from 'gatsby-image';

export default ({ data }) => {
  return (
    <Img
      fluid={{
        ...data.allContentfulAsset.edges[0].node.imgixImage.fluid,
        sizes: '100vw',
      }}
    />
  );
};

export const query = gql`
  {
    allContentfulAsset {
      edges {
        node {
          imgixImage {
            fluid(imgixParams: {
              // pass any imgix parameters you want to here
            }) {
              ...GatsbyImgixFluid
            }
          }
        }
      }
    }
  }
`;

A full list of imgix parameters can be found here.

Although sizes is optional, it is highly recommended. It has a default of (max-width: 8192px) 100vw, 8192px, which means that it is most likely loading an image too large for your users. Some examples of what you can set sizes as are:

  • 500px - the image is a fixed width. In this case, you should use fixed mode, described in the next section.
  • (min-width: 1140px) 1140px, 100vw - under 1140px, the image is as wide as the viewport. Above 1140px, it is fixed to 1140px.

Fixed Images

The following code will render a fixed image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.

import gql from 'graphql-tag';
import Img from 'gatsby-image';

export default ({ data }) => {
  return <Img fixed={data.allContentfulAsset.edges[0].node.imgixImage.fixed} />;
};

export const query = gql`
  {
    allContentfulAsset {
      edges {
        node {
          imgixImage {
            fixed(
              width: 960 # Width (in px) is required
              imgixParams: {}
            ) {
              ...GatsbyImgixFixed
            }
          }
        }
      }
    }
  }
`;

A full list of imgix parameters can be found here.

Generating imgix URLs

If you would rather not use gatsby-image and would instead prefer just a plain imgix URL, you can use the url field to generate one. For instance, you could generate a URL and use it for the background image of an element:

import gql from 'graphql-tag';

export default ({ data }) => {
  return (
    <div
      style={{
        backgroundImage: `url(${data.allContentfulAsset.edges[0].node.imgixImage.url})`,
        backgroundSize: 'contain',
        width: '100vw',
        height: 'calc(100vh - 64px)',
      }}
    >
      <h1>Blog Title</h1>
    </div>
  );
};

export const query = gql`
  {
    allContentfulAsset {
      edges {
        node {
          imgixImage {
            url(imgixParams: { w: 1200, h: 800 })
          }
        }
      }
    }
  }
`;

GraphQL imgixImage API

This feature can be best thought about as a replacement for gatsby-image-sharp for images that are statically defined at build time. This allows imgix URLs to be used with gatsby-image through the Gatsby GraphQL API. This feature transforms imgix URLs into a format that is compatible with gatsby-image. This can generate either fluid or fixed images. With this feature you can either display images that already exist on imgix, or proxy other images through imgix.

This feature supports many of the existing gatsby-image GraphQL that you know and love, and also supports most of the features of gatsby-image, such as blur-up and lazy loading. It also brings all of the great features of imgix, including the extensive image transformations and optimisations, as well as the excellent imgix CDN.

Configuration

This source must be configured in your gatsby-config file as follows:

module.exports = {
  //...
  plugins: [
    // your other plugins here
    {
      resolve: `@imgix/gatsby`,
      options: {
        domain: '<your imgix domain, e.g. acme.imgix.net>',
        defaultImgixParams: { auto: ['compress', 'format'] },
      },
    },
  ],
};

Setting { auto: ['compress', 'format'] } is highly recommended. This will re-format the image to the format that is best optimized for your browser, such as WebP. It will also reduce unnecessary wasted file size, such as transparency on a non-transparent image. More information about the auto parameter can be found here.

GatsbyImage support

This plugin now supports the latest GatsbyImage component, which delivers better performance and Lighthouse scores, while improving the developer experience.

To use this plugin with GatsbyImage, the usage is quite similar to the normal usage with gatsby-plugin-image. This plugin exposes a gatsbyImageData GraphQL field which is very similar to the native field.

Example:

import gql from 'graphql-tag';
import Img from 'gatsby-image';
import { GatsbyImage } from 'gatsby-plugin-image';

export default ({ data }) => {
  return <GatsbyImage image={data.imgixImage.gatsbyImageData} />;
};

export const query = gql`
  {
    imgixImage(url: "https://assets.imgix.net/amsterdam.jpg") {
      gatsbyImageData(width: 400, imgixParams: {})
    }
  }
`;
Shared field params

The layout, width, height, aspectRatio, outputPixelDensities, breakpoints, sizes, and backgroundColor parameters are identical to the parameters offered by the native gatsbyImageData field, and the documentation for those fields can be found in the Gatsby documentation. The other added parameters are specific to imgix and they are documented in the GraphQL type definitions, which can be explored in GraphiQL (usually at http://localhost:8000/__graphiql)

Fluid Images

The following code will render a fluid image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.

import gql from 'graphql-tag';
import Img from 'gatsby-image';

export default ({ data }) => {
  return <Img fluid={{ ...data.imgixImage.fluid, sizes: '100vw' }} />;
};

export const query = gql`
  {
    imgixImage(url: "/image.jpg") {
      fluid(imgixParams: {
        // pass any imgix parameters you want to here
      }) {
        ...GatsbyImgixFluid
      }
    }
  }
`;

A full list of imgix parameters can be found here.

Although sizes is optional, it is highly recommended. It has a default of (max-width: 8192px) 100vw, 8192px, which means that it is most likely loading an image too large for your users. Some examples of what you can set sizes as are:

  • 500px - the image is a fixed width. In this case, you should use fixed mode, described in the next section.
  • (min-width: 1140px) 1140px, 100vw - under 1140px, the image is as wide as the viewport. Above 1140px, it is fixed to 1140px.

Fixed Images

The following code will render a fixed image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.

import gql from 'graphql-tag';
import Img from 'gatsby-image';

export default ({ data }) => {
  return <Img fixed={data.imgixImage.fixed} />;
};

export const query = gql`
  {
    imgixImage(url: "/image.jpg") {
      fixed(
        width: 960 # Width (in px) is required
        imgixParams: {}
      ) {
        ...GatsbyImgixFixed
      }
    }
  }
`;

A full list of imgix parameters can be found here.

Generating imgix URLs

If you would rather not use gatsby-image and would instead prefer just a plain imgix URL, you can use the url field to generate one. For instance, you could generate a URL and use it for the background image of an element:

import gql from 'graphql-tag';

export default ({ data }) => {
  return (
    <div
      style={{
        backgroundImage: `url(${data.imgixImage.url})`,
        backgroundSize: 'contain',
        width: '100vw',
        height: 'calc(100vh - 64px)',
      }}
    >
      <h1>Blog Title</h1>
    </div>
  );
};

export const query = gql`
  {
    imgixImage(url: "/image.jpg") {
      url(imgixParams: { w: 1200, h: 800 })
    }
  }
`;

Using a Web Proxy Source

If you would like to proxy images from another domain, you should set up a Web Proxy Source. After doing this, you can use this source with this plugin as follows:

  1. Set the plugin config in gatsby-config.js to the following:
module.exports = {
  //...
  plugins: [
    // your other plugins here
    {
      resolve: `@imgix/gatsby-source-url`,
      options: {
        domain: '<your proxy source domain, e.g. my-proxy-source.imgix.net>',
        secureURLToken: '...', // <-- now required, your "Token" from your source page
        defaultImgixParams: ['auto', 'format'],
      },
    },
  ],
};
  1. Pass a fully-qualified URL to the url parameter in the GraphQL API. For example, to render a fixed image, a page would look like this:
import gql from 'graphql-tag';
import Img from 'gatsby-image';

export default ({ data }) => {
  return <Img fixed={data.imgixImage.fixed} />;
};

export const query = gql`
  {
    imgixImage(url: "https://acme.com/my-image-to-proxy.jpg") {
      # Now this is a full URL
      fixed(
        width: 960 # Width (in px) is required
      ) {
        ...GatsbyImgixFixed
      }
    }
  }
`;

URL Transform Function

This features allows imgix urls to be used with gatsby-image or gatsby-plugin-image. imgix urls are transformed into a format that is compatible with gatsby-image. This can generate either fluid, fixed images, or for gatsby-plugin-image, full-width, constrained, or fixed images. With this feature you can either display images that already exist on imgix, or proxy other images through imgix. It is important to note that this feature can only display images that are already on imgix or an imgix-compatible URL. To display images that are not using imgix, you will have to use one of the GraphQL APIs above.

โš ๏ธ This means that Web Proxy Sources are not supported with this API. To use Web Proxy Sources, either of the other two APIs must be used.

Unfortunately, due to limitations of Gatsby, this feature does not support blurred placeholders. To use placeholders please use one of the other use cases/parts of this library

Gatsby-plugin-image Component and Hook

This plugin supports the new frontend Gatsby-plugin-image component. To use the component with this plugin, use the following code

import { ImgixGatsbyImage } from '@imgix/gatsby';

export const MyPageComponent = () => {
  return (
    <ImgixGatsbyImage
      // Must be an imgix URL
      src="https://assets.imgix.net/amsterdam.jpg"
      // This can be used to set imgix params
      imgixParams={{ crop: 'faces' }}
      // These are passed through to the gatsby-plugin-image component
      layout="constrained"
      width={768}
      // Set either
      aspectRatio={16 / 9}
      // or
      sourceWidth={5000}
      sourceHeight={4000}

      // Any other props offered by the gatsby-plugin-image component are
      // supported and passed straight through to the component
    />
  );
};

If you would like more control over the data flow, you can also use the hook that this package exports - getGatsbyImageData - like so:

import { getGatsbyImageData } from '@imgix/gatsby';
import { GatsbyImage } from 'gatsby-plugin-image';

export const MyPageComponent = () => {
  return <GatsbyImage
    image={getGatsbyImageData({
      // Must be an imgix URL
      src: "https://assets.imgix.net/amsterdam.jpg"
      // This can be used to set imgix params
      imgixParams: { crop: 'faces' }

      // These are passed through to the gatsby-plugin-image component
      layout: "constrained"
      width: 768

      // Set either
      aspectRatio: 16 / 9
      // or
      sourceWidth: 5000
      sourceHeight: 4000
    })}
  >
}

Basic Fluid Image

The following code will render a fluid image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.

import Img from 'gatsby-image';
import { buildFluidImageData } from '@imgix/gatsby';

// Later, in a gatsby page/component.
<Img
  fluid={buildFluidImageData(
    'https://assets.imgix.net/examples/pione.jpg',
    {
      // imgix parameters
      ar: 1.61, // required
      auto: ['format', 'compress'], // recommended for all images
      // pass other imgix parameters here, as needed
    },
    {
      sizes: '50vw', // optional, but highly recommended
    },
  )}
/>;

ar is required, since gatsby-image requires this to generate placeholders. This ar will also crop the rendered photo from imgix to the same aspect ratio. If you don't know the aspect ratio of your image beforehand, it is virtually impossible to use gatsby-image in this format, so we either recommend using another of our plugins, or using an img directly.

Setting auto: ['format', 'compress'] is highly recommended. This will re-format the image to the format that is best optimized for your browser, such as WebP. It will also reduce unnecessary wasted file size, such as transparency on a non-transparent image. More information about the auto parameter can be found here.

A full list of imgix parameters can be found here.

Although sizes is optional, it is highly recommended. It has a default of 100vw, which means that it might be loading an image too large for your users. Some examples of what you can set sizes as are:

  • 500px - the image is a fixed width. In this case, you should use fixed mode, described in the next section.
  • (min-width: 1140px) 1140px, 100vw - under 1140px, the image is as wide as the viewport. Above 1140px, it is fixed to 1140px.

A full example of a fluid image in a working Gatsby repo can be found on CodeSandbox.

Edit @imgix/gatsby Fluid Example

Basic Fixed Image

The following code will render a fixed image with gatsby-image. This code should already be familiar to you if you've used gatsby-image in the past.

import Img from 'gatsby-image';
import { buildFixedImageData } from '@imgix/gatsby';

// Later, in a gatsby page/component.
<Img
  fixed={buildFixedImageData('https://assets.imgix.net/examples/pione.jpg', {
    // imgix parameters
    w: 960, // required
    h: 540, // required
    auto: ['format', 'compress'], // recommended for all images
    // pass other imgix parameters here, as needed
  })}
/>;

The imgix parameters w and h are required, since these are used by gatsby-image to display a placeholder while the image is loading. Other imgix parameters can be added below the width and height.

Setting auto: ['format', 'compress'] is highly recommended. This will re-format the image to the format that is best optimized for your browser, such as WebP. It will also reduce unnecessary wasted file size, such as transparency on a non-transparent image. More information about the auto parameter can be found here.

A full list of imgix parameters can be found here.

An example of this mode in a full working Gatsby repo can be found on CodeSandbox.

Edit @imgix/gatsby Fixed Example

API

GraphQL

The majority of the API for this library can be found by using the GraphiQL inspector (usually at https://localhost:8000/__graphql).

GraphQL Fragments

This library also provides some GraphQL fragments, such as GatsbyImgixFluid, and GatsbyImgixFluid_noBase64. The values of these fragments can be found at fragments.js

Gatsby/Plugin Configuration

The plugin options that can be specified in gatsby-config.js are:

Name Type Required Description
domain String The imgix domain to use for the image URLs. Usually in the format .imgix.net
defaultImgixParams Object Imgix parameters to use by default for every image. Recommended to set to { auto: ['compress', 'format'] }.
disableIxlibParam Boolean Set to true to remove the ixlib param from every request. See this section for more information.
secureURLToken String When specified, this token will be used to sign images. Read more about securing images on the imgix Docs site.

URL Transform Function

buildFixedImageData

function buildFixedImageData(
  /**
   * An imgix url to transform, e.g. https://yourdomain.imgix.net/your-image.jpg
   */
  url: string,
  /**
   * A set of imgix parameters to apply to the image.
   * Parameters ending in 64 will be base64 encoded.
   * A full list of imgix parameters can be found here: https://docs.imgix.com/apis/url
   * Width (w) and height (h) are required.
   */
  imgixParams: { w: number; h: number } & IImgixParams,
  /**
   * Options that are not imgix parameters.
   * Optional.
   */
  options?: {
    /**
     * Disable the ixlib diagnostic param that is added to every url.
     */
    includeLibraryParam?: boolean;
  },
): {
  width: number;
  height: number;
  src: string;
  srcSet: string;
  srcWebp: string;
  srcSetWebp: string;
};

buildFluidImageData

export function buildFluidImageData(
  /**
   * An imgix url to transform, e.g. https://yourdomain.imgix.net/your-image.jpg
   */
  url: string,
  /**
   * A set of imgix parameters to apply to the image.
   * Parameters ending in 64 will be base64 encoded.
   * A full list of imgix parameters can be found here: https://docs.imgix.com/apis/url
   * The aspect ratio (ar) as a float is required.
   */
  imgixParams: {
    /**
     * The aspect ratio to set for the rendered image and the placeholder.
     * Format: float or string. For float, it can be calculated with ar = width/height. For a string, it should be in the format w:h.
     */
    ar: number | string;
  } & IImgixParams,
  /**
   * Options that are not imgix parameters.
   * Optional.
   */
  options?: {
    /**
     * Disable the ixlib diagnostic param that is added to every url.
     */
    includeLibraryParam?: boolean;
    /**
     * The sizes attribute to set on the underlying image.
     */
    sizes?: string;
  },
): {
  aspectRatio: number;
  src: string;
  srcSet: string;
  srcWebp: string;
  srcSetWebp: string;
  sizes: string;
};

Third-party integration helpers (e.g. for Gatsby source plugins)

This section is for third-party plugin developers of Gatsby plugins and sources that would like to expose the functionality of this library inside their own plugins natively. For example, the Prismic Gatsby plugin uses these APIs to expose fixed, fluid, url, and gatsbyImageData fields on its images that it exposes in its GraphQL API.

createImgixGatsbyTypes

This is the main function that should be used to reuse functionality from this library.

API
Parameter Type Required Description
imgixClientOptions Object Any extra configuration to pass to new ImgixClient from @imgix/js-core (see here for more information).
resolveUrl (source) => string | undefined โœ” A callback to resolve the image URL from the source data provided to the resolver. The source data is provided by the resolver of the type you are adding the image fields too.
resolveWidth (source) => number | undefined This callback can be used to provide the source (uncropped) width of the target image from the source data, if known. The data passed to this callback is the same as is passed to resolveUrl. If this callback is not provided, a network request will be made at build time to resolve this information.
resolveHeight (source) => number | undefined This callback can be used to provide the source (uncropped) height of the target image from the source data, if known. The data passed to this callback is the same as is passed to resolveUrl. If this callback is not provided, a network request will be made at build time to resolve this information.
allowListFields Array This can be used to restrict the types and fields generated to avoid creating extra unnecessary types. Possible values: url, fixed, fluid, gatsbyImageData.
defaultParams Object Default imgix parameters to apply for these images.
namespace String Prepends the types generated by this library with the supplied namespace to avoid name collisions. It is recommended to set this to something unique to your library so that if your developers import another Gatsby plugin that also this plugin that the names do not collide.
cache GatsbyCache โœ” The Gatsby cache provided to Gatsby API hooks
Code example
// gatsby-node.js
const imgixGatsby = require('@imgix/gatsby/dist/pluginHelpers');

exports.createSchemaCustomization = async (gatsbyContext, options) => {
  const imgixTypes = imgixGatsby.createImgixGatsbyTypes({
    cache: gatsbyContext.cache,
    resolveUrl: (node) => node.imageURL,
    resolveWidth: (node) => node.imageSourceWidth,
    resolveHeight: (node) => node.imageSourceHeight,
    defaultParams: { auto: 'compress,format' },
    namespace: 'Imgix',
    imgixClientOptions: {
      // domain is required if urls are not already imgix urls. If a domain is provided here, and the image urls are not imgix urls, the the imgix source needs to be a web proxy source, and a secureURLToken token is required (see below).
      domain: 'my-imgix-domain.imgix.net',
      // secureURLToken is required if imgix source type is web proxy, or "secure URLs" is enabled in the imgix configuration dashboard
      secureURLToken: 'my-secure-url-token',
    },
  });

  const myNodeType = gatsbyContext.schema.buildObject({
    name: 'MyPluginNodeType',
    fields: {
      // Your other node fields, e.g. title, description, etc
      title: { type: 'String!' },

      // Add the fields returned from createImgixGatsbyTypes to your node as fields
      imageUrl: imgixTypes.fields.url,
      fluid: imgixTypes.fields.fluid,
      fixed: imgixTypes.fields.fixed,
      gatsbyImageData: imgixTypes.fields.gatsbyImageData,
    },
  });

  gatsbyContext.actions.createTypes([
    ...imgixTypes.types.map(gatsbyContext.schema.buildObjectType),
    ...imgixTypes.enumTypes.map(gatsbyContext.schema.buildEnumType),
    ...imgixTypes.inputTypes.map(gatsbyContext.schema.buildInputObjectType),
  ]);
  gatsbyContext.actions.createTypes(myNodeType);
};

Object builders

These low-level functions can be used to build data that can be passed straight to gatsby-image, or gatsby-plugin-image, if necessary. It is recommended to use createImgixGatsbyTypes instead of these functions.

buildFluidObject
import { buildFluidObject } from '@imgix/gatsby/dist/pluginHelpers';
import Img from 'gatsby-image';

const fluidData = buildFluidObject({
  // Image url, required. See note in section 'Note about url and imgixClientOptions' about what to do based on what kind of url this is
  url: 'https://domain.imgix.net/amsterdam.jpg',
  // Any extra configuration to pass to new ImgixClient from @imgix/js-core (see [here](https://github.com/imgix/js-core#configuration) for more information)
  imgixClientOptions: {
    domain: 'domain.imgix.net',
    secureURLToken: 'secure-token',
  },
  // Mimicking GraphQL field args
  args: {
    // Imgix params, required (at least {})
    imgixParams: {},
    // Imgix params for the placeholder image, required (at least {})
    placeholderImgixParams: {},
    // Max image width srcset to generate, required.
    maxWidth: 8192,
    // Max image height to generate, optional.
    maxHeight: 5000,
    // Custom src set breakpoints to set, optional.
    srcSetBreakpoints: [100, 200],
  },
  // The height in px of the original image, required
  sourceHeight: 3000,
  // The width in px of the original image, required
  sourceWidth: 4000,
  // Default params to set, required
  defaultParams: {},
  // Default placeholder params to set, required
  defaultPlaceholderParams: {},
});

// In component later...
<Img fluid={fluid} />;
buildFixedObject
import { buildFixedObject } from '@imgix/gatsby/dist/pluginHelpers';
import Img from 'gatsby-image';

const fixedData = buildFixedObject({
  // Image url, required. See note in section 'Note about url and imgixClientOptions' about what to do based on what kind of url this is
  url: 'https://domain.imgix.net/amsterdam.jpg',
  // Any extra configuration to pass to new ImgixClient from @imgix/js-core (see [here](https://github.com/imgix/js-core#configuration) for more information)
  imgixClientOptions: {
    domain: 'domain.imgix.net',
    secureURLToken: 'secure-token',
  },
  // Mimicking GraphQL field args
  args: {
    // Imgix params, required (at least {})
    imgixParams: {},
    // Imgix params for the placeholder image, required (at least {})
    placeholderImgixParams: {},
    // The width of the image in px for the 1x image, required.
    width: 100,
    // The height of the image in px for the 1x image, optional
    height: 200,
    // The imgix quality param to set, optional.
    quality: 50,
  },
  // The height in px of the original image, required
  sourceHeight: 3000,
  // The width in px of the original image, required
  sourceWidth: 4000,
  // Default params to set, required
  defaultParams: {},
  // Default placeholder params to set, required
  defaultPlaceholderParams: {},
});

// In component later...
<Img fixed={fixed} />;
buildGatsbyImageDataObject
import { buildGatsbyImageDataObject } from '@imgix/gatsby/dist/pluginHelpers';
import { GatsbyImage } from 'gatsby-plugin-image';

const gatsbyImageData = buildGatsbyImageDataObject({
  // Image url, required. See note in section 'Note about url and imgixClientOptions' about what to do based on what kind of url this is
  url: 'https://domain.imgix.net/amsterdam.jpg',
  // Any extra configuration to pass to new ImgixClient from @imgix/js-core (see [here](https://github.com/imgix/js-core#configuration) for more information)
  imgixClientOptions: {
    domain: 'domain.imgix.net',
    secureURLToken: 'secure-token',
  },
  // Mimicking GraphQL field args
  resolverArgs: {
    // The gatsby-plugin-image layout parameter
    layout: 'fullWidth',
    // Imgix params, optional
    imgixParams: {},
    // Imgix params for the placeholder image, optional
    placeholderImgixParams: {},
    // The width or max-width (depending on the layout setting) of the image in px, optional.
    width: 100,
    // The height or max-height (depending on the layout setting) of the image in px, optional.
    height: 200,
    // The aspect ratio of the srcsets to generate, optional
    aspectRatio: 2,
    // Custom srcset breakpoints to use, optional
    breakpoints: [100, 200],
    // Custom 'sizes' attribute to set, optional
    sizes: '100vw',
    // Custom srcset max width, optional
    srcSetMaxWidth: 8000,
    // Custom srcset min width, optional
    srcSetMinWidth: 100,
    // The factor used to scale the srcsets up, optional.
    // E.g. if srcsetMinWidth is 100, then the srcsets are generated as follows
    // while (width < maxWidth) nextSrcSet = prevSrcSet * (1 + widthTolerance)
    widthTolerance: 0.08,
  },
  // source width and of the uncropped image
  dimensions: { width: 5000, height: 3000 },
});

<GatsbyImage image={gatsbyImageData} />;
Note about url and imgixClientOptions

Depending on what kind of image URL url is set to in the above object helpers, domain and secureURLToken might have to be passed in imgixClientOptions.

If url is:

  1. an imgix URL, domain and secureURLToken are likely not required. If domain is set, the source must be a Web Proxy Source. If "secure URLs" are enabled on the imgix source, or the source is a Web Proxy Source, secureURLToken is required.
  2. a path (e.g. just /image.jpg), domain is required, and the domain should point to an imgix S3, GCP, Azure, or Web Folder source. secureURLToken is only required if "secure URLs" are enabled on the imgix source.
  3. not an imgix URL, domain and secureURLToken are required, and domain should point to a Web Proxy imgix source.

Miscellaneous

What is the ixlib Param on Every Request?

For security and diagnostic purposes, we tag all requests with the language and version of the library used to generate the URL. To disable this, we provide two options.

For disabling the ixlib parameter across all requests, we provide disableIxlibParam as a plugin option for use in gatsby-config.js.

// gatsby-config.js
module.exports = {
  //...
  plugins: [
    // your other plugins here
    {
      resolve: `@imgix/gatsby`,
      options: {
        domain: '<domain.imgix.net>',
        disableIxlibParam: 'true', // this disables the ixlib parameter
        defaultImgixParams: { auto: ['compress', 'format'] },
      },
    },
  ],
};

For disabling ixlib on a case by case basis, we provide the includeLibraryParam parameter. When calling either of this library's two exported functions, in the third parameter set includeLibraryParam to false. For example, for buildFluidImageData:

<Img
  fluid={buildFixedImageData(
    'https://assets.imgix.net/examples/pione.jpg',
    {
      w: 960,
      h: 540,
    },
    {
      includeLibraryParam: false, // this disables the ixlib parameter
    },
  )}
/>

GraphQL Type Customization Warning

@imgix/gatsby customizes existing GraphQl types in order to expose our own types on those same fields. This allows for a more seamless integration with Gatsby. It also means that you might see a warning like this:

warn Plugin `@imgix/gatsby` has customized the GraphQL type `ShopifyCollectionImage`, which has already been defined by the plugin `gatsby-source-shopify`. This could potentially cause conflicts.

This warning can be safely ignored, ie this should not impact your build in any way.

This warning stems from the fact that type inference is "not allowed" in Gatsby plugins. In other words, Gatsby assumes that plugins are not modifying types that they do not own. Therefore it logs a warning whenever types are modified by a plugin that did not create them.

Gatsby does this in an effort to reduce the likelihood installing one plugin can break an entire build. If one plugin can change any plugin's type, it can break any plugin in the build. gatsby-imgix only modifies types that the user explicitly denotes as their image types. So we don't run the risk of overwriting or modifying types outside a source's explicitly denoted image types.

You can read more about this if youโ€™re interested in this issue.

Multiple imgix Sources

You might find yourself with multiple imgix sources and wondering how you could use them at the same time with this plugin. There are a few possibilities for this, which will be outlined below.

Any number of sources can be used simultaneously with the URL transform API.

Example:

import { ImgixGatsbyImage } from '@imgix/gatsby';

export const MyPageComponent = () => (
  <div>
    <ImgixGatsbyImage src="https://first-source.imgix.net/image.jpg" />
    <ImgixGatsbyImage src="https://second-source.imgix.net/image.jpg" />
  </div>
);

The caveats with this approach is that you don't get the benefits of the GraphQL APIs (blur-up, etc), and that the sources must not be Web Proxy sources (for these you must use one of the GraphQL APIs).

Additionally, a source can be configured for one of the GraphQL APIs, and this source can be a Web Proxy source. Thus seemingly you could combine one of the GraphQL APIs and the URL transform API together to use multiple sources this way:

import gql from 'graphql-tag';
import Img from 'gatsby-image';
import { GatsbyImage } from 'gatsby-plugin-image';
import { ImgixGatsbyImage } from '@imgix/gatsby';

export default ({ data }) => (
  <div>
    <GatsbyImage image={data.imgixImage.gatsbyImageData} />;
    <ImgixGatsbyImage src="https://second-source.imgix.net/image.jpg" />
  </div>
);

export const query = gql`
  {
    imgixImage(url: "https://assets.imgix.net/amsterdam.jpg") {
      gatsbyImageData(width: 400, imgixParams: {})
    }
  }
`;

So, to summarise, it is possible to use multiple sources in this plugin. You have the option to use up to one source of any type with the GraphQL API, and then any number of non-Web Proxy sources with the URL transform API.

Upgrade Guides

Upgrading from v1.x to v2

Between v1 and v2, the method to retrieve the image url in the GraphQL from the raw data was changed. This was done to support Gatsby v4, as function configuration options are no longer possible in Gatsby v4. If you do not use the GraphQL transform API, then you do not have to change anything.

To upgrade from v1 to v2, the following configuration options need to be updated:

// gatsby-config.js
module.exports = {
  plugins: {
    // ...
    {
      resolve: `@imgix/gatsby`,
      options: {
        // ...
        fields: [
          {
            nodeType: "Post",
            fieldName: "imgixImage",

            // The follow option needs to be changed...
            getURL: node => `https:${node.banner.imageURL}`,

            // to this:
            rawURLKey: "banner.imageURL",
            URLPrefix: "https:",
          },
        ],
      },
    },
  }
}

Upgrading from @imgix/gatsby-transform-url

@imgix/gatsby-transform-url was deprecated in favor of combining these sub-projects into one single project, for simplicity.

The functionality of that library can be found, unchanged, under this new package. Specifically, all that needs to changed is the import statements, e.g. from

import { buildFluidImageData } from '@imgix/gatsby-transform-url';

to

import { buildFluidImageData } from '@imgix/gatsby';

Contributors

Contributions are a vital part of this library and imgix's commitment to open-source. We welcome all contributions which align with this project's goals. More information can be found in the contributing documentation.

imgix would like to make a special announcement about the prior work of Angelo Ashmore from Wall-to-Wall Studios on his gatsby plugin for imgix. The code and API from his plugin has made a significant contribution to the codebase and API for imgix's official plugins, and imgix is very grateful that he agreed to collaborate with us.

Wall-to-Wall Studios Logo

Thanks goes to these wonderful people (emoji key):


Frederick Fogerty

๐Ÿ’ป ๐Ÿ“– ๐Ÿšง

Angelo Ashmore

๐Ÿ’ป

Luis H. Ball Jr.

๐Ÿ“–

Sherwin Heydarbeygi

๐Ÿ“–

This project follows the all-contributors specification.

License

FOSSA Status

gatsby's People

Contributors

allcontributors[bot] avatar angeloashmore avatar atlawrie avatar fossabot avatar frederickfogerty avatar luqven avatar renovate-bot avatar renovate[bot] avatar semantic-release-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gatsby's Issues

auto=format in Chrome 88 and above not serving WebP images

I wasn't sure where to post this bug which seems to be OS and framework independent FYI

Chrome 88 and above is serving images with auto=format in their original format. Not sure if this is related to the Safari bug mentioned in your documentation Here. Originally I thought this was a Gatsby v3 issue, then a DatoCMS issue but, now I believe it's a Chrome (Maybe Webkit in general) issue.

To Reproduce

  1. Go to URL
  2. Right-click on the image under the heading DatoCMS
  3. Save the image.

Test Repo - I created this test repo when I thought this was a CMS issue hence Image from Contentful and DatoCMS.

Here is a list of other sites I've found with the same behavior:

Expected behavior
Saving an image from a site should produce WebP if the platform supports it.

Information:
Most of my testing can be found here gatsby-source-datocms issue #164 and here Gatsby issue #31644. (sorry for the redundancy)

`fpZ` not working

Hello,

GraphQL does not allow hyphenated names. The property fpZ just get past to the generated URL and Imgix does not seem to know what to do with it (fpZ=1 instead of fp-z=1).

I'm using the version 1.6.0.

Thanks.

Warning during build when using with `gatsby-source-shopify`

Hi,

When I use @imgix/gatsby with gatsby-source-shopify I've been getting these warnings the entire time, although everything still builds and works as expected.

warn Plugin `@imgix/gatsby` has customized the GraphQL type `ShopifyCollectionImage`, which has already been defined by the plugin `gatsby-source-shopify`. This could potentially cause conflicts.
warn Plugin `@imgix/gatsby` has customized the GraphQL type `ShopifyProductImage`, which has already been defined by the plugin `gatsby-source-shopify`. This could potentially cause conflicts.
warn Plugin `@imgix/gatsby` has customized the GraphQL type `ShopifyProductVariantImage`, which has already been defined by the plugin `gatsby-source-shopify`. This could potentially cause conflicts.
warn Plugin `@imgix/gatsby` has customized the GraphQL type `ShopifyProductFeaturedImage`, which has already been defined by the plugin `gatsby-source-shopify`. This could potentially cause conflicts.

Just wondering what's causing them and if it's something to worry about?

Display images from Gatsby source through gatsby-image

This is a potential feature for this library. If you want to see us build this, please indicate your support by reacting to this with a ๐Ÿ‘

User Story

I have an image provided from a Gatsby source that Iโ€™d like to transform through imgix and display using gatsby-image.

Description

This is very similar to #3, but extends that feature to support gatsby-image, including lazy-loading, and blur-up.

Upload images from a local source to imgix

This is a potential feature for this library. If you want to see us build this, please indicate your support by reacting to this with a ๐Ÿ‘

User Story

I have an image stored locally that I want to upload to image-manager and render.

Description

This would offload the processing of images stored on a developer's machine to imgix. This results in much lower build times and also allows the developer to take advantage of imgix's larger suite of transformations, better responsiveness, and best-in-class CDN.

Building schema failed: Type `<type name>` declared in `createTypes` looks like a node, but doesn't implement a `Node` interface

Description

With @imgix/gatsby enabled, gatsby develop and gatsby build result in the following error:

warn Type ImagesJson declared in createTypes looks like a node, but doesn't implement a Node interface. It's likely that you should add the Node interface to your type def:
type ImagesJson implements Node { ... }
If you know that you don't want it to be a node (which would mean no root queries to retrieve it), you can explicitly disable inference for it:
type ImagesJson @dontInfer { ... }
ERROR
Building schema failed
not finished building schema - 0.106s

To Reproduce
I have the following tandem configured: gatsby-source-filesystem to read a json file called images.json with data, like this:

[
    {
        "url": "https://bucket.imgix.net/images/header/splash.jpg"
    }
]

then gatsby-transformer-json to parse the JSON file, and finally @imgix/gatsby with the following configuration:

        {
            resolve: "@imgix/gatsby",
            options: {
                domain: "bucket.imgix.net",
                sourceType: ImgixSourceType.AmazonS3,
                fields: [
                    {
                        nodeType: "ImagesJson",
                        getURL: (node) => node.url,
                        fieldName: 'image'
                    }
                ]
            }
        }

If I disable @imgix/gatsby in the config - build succeeds. The JSON is parsed just fine, verified in GraphiQL.

It appears to be clear that the issue is isolated to imgix/gatsby.

Expected behaviour
No error, and an images node with stuff added to my ImagesJson object. The configuration above used to work with gatsby-plugin-imgix and Gatsby v2 before.

Information:

  • imgix/gatsby version: 1.6.11
  • browser version: Version 1.25.72 Chromium: 91.0.4472.101 (Official Build) (64-bit)
  • OS used: Debian GNU/Linux 10 (buster)

Additional context
I'm happy to provide any additional information, if required.

Is it possible to use customized GraphQL fields?

Before you submit:

Question
I have added a field for image URL using Gatsby createResolvers API.

// gatsby-node.js
exports.createResolvers = ({ createResolvers }) => {
  createResolvers({
    Post: {
      imageUrl: {
        type: 'String!',
        resolve(source) {
          const getImageUrl = (text) => {
            // The process of extracting the image URL from text
          }
          return getImageUrl(source.text)
        },
      },
    },
  })
}

I can retrieve the value of the field using the following query:

export const query = graphql`
  {
    allPost {
      nodes {
        text # Text containing the image URL
        imageUrl # https://...
      }
    }
  }
`

I have configured the field, but when I execute the query, an error occurs.

// gatsby-config.js
module.exports = {
  //...
  plugins: [
    //... other plugins
    {
      resolve: `@imgix/gatsby`,
      options: {
        defaultImgixParams: { auto: ['compress', 'format'] },
        fields: [
          {
            nodeType: 'Post',
            fieldName: 'imgixImage',
            rawURLKey: 'imageUrl',
          },
        ],
      },
    },
  ],
};

Error:

Error when resolving URL value for node type Post. This probably means that the rawURLKey function in gatsby-config.js is incorrectly set. Please read this project's README for detailed instructions on how to set this correctly.

Is it possible to use customized GraphQL fields?

Display images from imgix source with gatsby-image

This is a potential feature for this library. If you want to see us build this, please indicate your support by reacting to this with a ๐Ÿ‘

User Story

I have an image stored in an imgix source (e.g. Amazon S3/GCP) that I want to display using gatsby-image.

Description

This would allow developers that already have an imgix source configured, and with images already available from those sources, to display those images with gatsby-image.

fix: Invalid plugin options for "@imgix/gatsby" - "domain" is required

We're upgrading from v2.0.3 to v2.0.4 of this library and we started receiving such error on gatsby develop:

success load gatsby config - 0.088s
ERROR #11331 PLUGIN
Invalid plugin options for "@imgix/gatsby":

  • "domain" is required

The release notes for v2.0.4 doesn't list any changes in the way how the domain setting logic is handled, which makes us think that this is a bug.

This is the configuration we use:

{
    resolve: "@imgix/gatsby",
    options: {
        domain: "", // keep it empty, since we want to preserve domain name together with the link
        sourceType: ImgixSourceType.AmazonS3,
        fields: [
            {
                nodeType: "ImagesJson",
                rawURLKey: "url",
                fieldName: "image"
            }
        ],
        disableIxlibParam: true
    }
}

We intentionally set domain to be empty because we want to keep the full URL of our imgix images in our components.

The README.md states:

If url is: an imgix URL, domain and secureURLToken are likely not required. If domain is set, the source must be a Web Proxy Source. If "secure URLs" are enabled on the imgix source, or the source is a Web Proxy Source, secureURLToken is required.

We tried removing the domain parameter from the config entirely as the docs suggest that it's optional, but we receive the same error.

What can be done about this? Thank you in advance!

`disableIxlibParam` doesn't work

  1. The disableIxlibParam setting doesn't work. When it is not set (or set to false), the URLs generated look like this: https://domain.net/image.jpg?ixlib=gatsbySourceUrl-2.0.2. When it is set to true, the URLs look like this: https://domain.net/image.jpg?ixlib=js-3.5.1.

I expect that disableIxlibParam should disable any variation of ixlib param.

  1. Another question is why something that's claimed to be a diagnostic mechanism is enabled by default? Can we switch it off by default? Imagine that a security vulnerability is found in a specific version of a plugin. Exposing the version of the library in the URLs of every image can expedite identification of many vulnerable sites that use this specific version.

  2. The documentation (README.md) has some discrepancies: sometimes it says that do disable the ixlib param, one needs to set includeLibraryParam to false, other times it says that in order to disable it, disableIxlibParam should be set to true. None of this settings (and their combination) allows to disable the version of the library entirely.

Information:

  • imgix/gatsby version: 2.0.3
  • browser version: Chrome 104

feat: gracefully handle empty image URL fields

How do you handle a source that may or may not have a value for a field?

I have content sourced from a Google Spreadsheet, this spreadsheet has a column called img with a URL to a publicly accessible image. This column might be null or have a string.

To debug the setup I configured the plugin without a defined rawURLKey and produced this error:

Error when resolving URL value for node type googleReviewsSheet. This probably means that the rawURLKey function
in gatsby-config.js is incorrectly set. Please read this project's README for detailed instructions on how to
set this correctly.

Potential images were found at these paths:
 - img
   Set following configuration options:
     rawURLKey: 'img'
     URLPrefix: 'https:'

When configuring the plugin with the suggestions and settings I think are correct, like this:

{
  resolve: `@imgix/gatsby`,
  options: {
    domain: "example.imgix.net",
    secureURLToken: "abc123",
    sourceType: ImgixSourceType.WebProxy,
    defaultImgixParams: { auto: "format,compress" },
    fields: [
      {
        nodeType: "googleReviewsSheet",
        fieldName: "imgixImage",
        rawURLKey: "img",
        URLPrefix: "https:",
      },
    ],
  },
},

The following error is thrown and the build or develop task crashes.

Error when resolving URL value for node type googleReviewsSheet. This probably means that the rawURLKey function 
in gatsby-config.js is incorrectly set. Please read this project's README for detailed instructions on how to 
set this correctly.

Everything seems to work fine if the source has a string populated for every record.

Fragment partial that for getting image data:

{
  ...
  id
  verifiedPurchase
  rating
  imgixImage {
    gatsbyImageData(
      imgixParams: {
        fit: "crop"
        crop: "faces,entropy"
        fill: "blur"
        w: 280
        h: 200
      }
      width: 282
      height: 200
      placeholder: DOMINANT_COLOR
    )
  }
}

Pre version 2 it seemed possible to work around the error by using something likegetURL: (node) => node.img || 'https://example.com/file.jpg'

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): replace dependency @google/semantic-release-replace-plugin with semantic-release-replace-plugin
  • fix(deps): replace dependency read-pkg-up with read-package-up ^11.0.0
  • chore(dev-deps): update dependency @types/common-tags to v1.8.4
  • chore(dev-deps): update dependency @types/is-base64 to v1.1.3
  • chore(dev-deps): update dependency @types/lodash.get to v4.4.9
  • chore(dev-deps): update dependency @types/node-fetch to v2.6.11
  • chore(deps): update actions/add-to-project action to v0.6.1
  • chore(deps): update node orb to v5.2.0
  • chore(dev-deps): update dependency @google/semantic-release-replace-plugin to v1.2.7
  • chore(dev-deps): update dependency eslint to v8.57.0
  • chore(dev-deps): update gatsby monorepo (gatsby, gatsby-plugin-image, gatsby-plugin-sharp, gatsby-source-filesystem)
  • chore(dev-deps): update react monorepo to v18.3.1 (react, react-dom)
  • fix(deps): update dependency ramda to ^0.30.0 (ramda, @types/ramda)
  • chore(deps): update actions/add-to-project action to v1
  • chore(deps): update actions/checkout action to v4
  • chore(deps): update dependency chalk to v5
  • chore(deps): update wagoid/commitlint-github-action action to v6
  • chore(dev-deps): update dependency conventional-changelog-conventionalcommits to v8
  • chore(dev-deps): update dependency eslint to v9
  • chore(dev-deps): update dependency marked to v12
  • chore(dev-deps): update dependency prettier to v3
  • chore(dev-deps): update dependency read-pkg to v9
  • chore(dev-deps): update dependency semantic-release to v23
  • chore(dev-deps): update dependency typescript to v5
  • chore(dev-deps): update jest monorepo to v29 (major) (@types/jest, jest, ts-jest)
  • fix(deps): update dependency camel-case to v5
  • fix(deps): update dependency read-pkg-up to v11
  • chore(deps): lock file maintenance
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

circleci
.circleci/config.yml
  • node 5.0.3
  • browser-tools 1.4.0
dockerfile
.codesandbox/Dockerfile
github-actions
.github/workflows/add-issue-to-project.yml
  • actions/add-to-project v0.4.0
.github/workflows/add-pr-to-project.yml
  • actions/add-to-project v0.4.0
.github/workflows/commitlint.yml
  • actions/checkout v3
  • wagoid/commitlint-github-action v4
npm
package.json
  • @imgix/js-core 3.6.0
  • camel-case ^4.1.2
  • common-tags ^1.8.0
  • debug ^4.3.1
  • graphql-compose ^9.0.0
  • imgix-url-params ^11.15.0
  • joi ^17.6.0
  • jsuri ^1.3.1
  • lodash.get ^4.4.2
  • node-fetch ^2.6.0
  • ramda ^0.27.1
  • read-pkg-up ^9.0.0
  • @babel/core 7.19.6
  • @babel/eslint-parser 7.19.1
  • @google/semantic-release-replace-plugin 1.1.0
  • @semantic-release/changelog 6.0.3
  • @semantic-release/git 10.0.1
  • @types/common-tags 1.8.1
  • @types/is-base64 1.1.1
  • @types/jest 27.5.2
  • @types/jsuri 1.3.30
  • @types/lodash.get 4.4.7
  • @types/node-fetch 2.6.2
  • @types/ramda 0.27.44
  • babel-eslint 10.1.0
  • conventional-changelog-conventionalcommits 4.6.3
  • cross-env 7.0.3
  • eslint 8.45.0
  • gatsby 5.3.2
  • gatsby-image ^3.11.0
  • gatsby-plugin-image 3.3.2
  • gatsby-plugin-sharp 5.3.2
  • gatsby-source-filesystem 5.3.1
  • graphql ^16.6.0
  • graphql-tag 2.12.6
  • is-base64 1.1.0
  • jest 27.5.1
  • marked 4.3.0
  • msync 2.5.10
  • prettier 2.2.1
  • react 18.2.0
  • react-dom 18.2.0
  • read-pkg 5.2.0
  • semantic-release 19.0.5
  • ts-jest 27.1.5
  • typescript 4.7.4
  • webpack 5.74.0
  • yarn-run-all 3.1.1
  • gatsby ^2 || ^3 || ^4 || ^5
  • gatsby-image ^2 || ^3
  • gatsby-plugin-image ^1 || ^2 || ^3
  • chalk ^4
  • graphql ^16.6.0
  • graphql-compose ^9.0.0
  • webpack 5.74.0

  • Check this box to trigger a request for Renovate to run again on this repository

ERROR @imgix/gatsby not working at all at build proccess

@imgix/gatsby is not working any more on build process using the command gatsby build.
I have the following error:

info [@imgix/gatsby] Loaded plugin.                                                                                                                                                                                                                                                                                     
success onPreInit - 0.011s
success initialize cache - 0.059s
success copy gatsby files - 0.155s
success Compiling Gatsby Functions - 0.235s
success onPreBootstrap - 0.895s

 ERROR #11321  PLUGIN

"@imgix/gatsby" threw an error while running the createSchemaCustomization lifecycle:

Cannot read properties of undefined (reading 'slice')

  145 |
  146 |   // Create the imgix GraphQL types, which will be added to the schema later
> 147 |   const typesAndFields = buildImgixGatsbyTypes<{ rawURL: string }>({
      |                                               ^
  148 |     cache: gatsbyContext.cache,
  149 |     imgixClient,
  150 |     resolveUrl: prop('rawURL'),

File: node_modules\@imgix\gatsby\src\modules\gatsby-plugin\gatsby-node.ts:147:47



  TypeError: Cannot read properties of undefined (reading 'slice')

  - graphqlTypes.ts:57
    [youmni-front]/[@imgix]/gatsby/src/modules/gatsby-plugin/graphqlTypes.ts:57:35

  - Array.reduce

  - graphqlTypes.ts:24 ImgixParamsInputType
    [youmni-front]/[@imgix]/gatsby/src/modules/gatsby-plugin/graphqlTypes.ts:24:54

  - typeBuilder.ts:55 buildImgixGatsbyTypes
    [youmni-front]/[@imgix]/gatsby/src/modules/gatsby-plugin/typeBuilder.ts:55:47

  - gatsby-node.ts:147
    [youmni-front]/[@imgix]/gatsby/src/modules/gatsby-plugin/gatsby-node.ts:147:47

  - gatsby-node.js:33 step
    [youmni-front]/[@imgix]/gatsby/dist/modules/gatsby-plugin/gatsby-node.js:33:23

  - gatsby-node.js:14 Object.next
    [youmni-front]/[@imgix]/gatsby/dist/modules/gatsby-plugin/gatsby-node.js:14:53

  - gatsby-node.js:8
    [youmni-front]/[@imgix]/gatsby/dist/modules/gatsby-plugin/gatsby-node.js:8:71

  - new Promise

  - gatsby-node.js:4 __awaiter
    [youmni-front]/[@imgix]/gatsby/dist/modules/gatsby-plugin/gatsby-node.js:4:12

  - gatsby-node.ts:125 Object.createSchemaCustomization
    [youmni-front]/[@imgix]/gatsby/src/modules/gatsby-plugin/gatsby-node.ts:125:11

  - api-runner-node.js:430 runAPI
    [youmni-front]/[gatsby]/src/utils/api-runner-node.js:430:22

  - api-runner-node.js:581 Promise.catch.decorateEvent.pluginName
    [youmni-front]/[gatsby]/src/utils/api-runner-node.js:581:13

  - debuggability.js:384 Promise._execute
    [youmni-front]/[bluebird]/js/release/debuggability.js:384:9

  - promise.js:518 Promise._resolveFromExecutor
    [youmni-front]/[bluebird]/js/release/promise.js:518:18

  - promise.js:103 new Promise
    [youmni-front]/[bluebird]/js/release/promise.js:103:10


not finished createSchemaCustomization - 0.124s

After investigation, the source of the problem is due to the latest changes to the imgix-url-params pacakge with the version 11.15.0. A rollback to the version 11.13.1 solved the problem. I believe that the exception thrown after calling the slice method as mentioned in the error is caused by the lack of short_description for the parameter parameters node in this json file.

I used the versions 1.7.7 and 2.1.2 of @imgix/gatsby, the same problem.

Use multiple sources within the same project

Before you submit:

Question
Is it possible to use images from multiple imgix sources within the same Gatsby project? E.g. images from a CMS (through a Web Proxy Source) and images from a S3 bucket (through a Amazon S3 Source)?

Thanks for any hints.

Blur-up and lazyload gatsby-image support

This is a potential feature for this library. If you want to see us build this, please indicate your support by reacting to this with a ๐Ÿ‘

User Story

I want to display imgix images with gatsby-image's lazy-load and blur-up features.

Gatsby source for images from image manager

This is a potential feature for this library. If you want to see us build this, please indicate your support by reacting to this with a ๐Ÿ‘

User Story

I have an image stored in image manager that I want to render.

Description

This would provide a Gatsby source that would allow developers to display any images available in imgix's new image manager product.

For example, in a Gatsby page query:

{
	allImgixImages {
		name
		url(imgixParams: {auto: ["compress"]}) { url }
		owner
		modifiedAt
	}
}

feat: support for images within markdown

It doesn't seem like processing images within markdown is supported with this plugin, similar to something like what gatsby-remark-images does.

It seems like processing image links in the frontmatter is not a problem as shown here, but I'm wondering if there is any plan to support images within the markdown body itself.

AVIF format not showing

I'm using ImgixGatsbyImage on Gatsby v4 but setting auto:['format']as imgixParams still serve a JPG and not an AVIF image.
Using the local version of the .JPG image with gatsby-plugin-image serve an AVIF

What's wrong here?

<ImgixGatsbyImage
  src="https://mysource.imgix.net/image.jpg"
  imgixParams={{ crop: 'faces', auto: ['compress', 'format'] }}
  layout="fullWidth"
  aspectRatio={3 / 2}
  alt="test"
/>
<StaticImage
    src="../images/image.jpg"
    layout="fullWidth"
    alt="test"
/>

Transform images from gatsby sources

This is a potential feature for this library. If you want to see us build this, please indicate your support by reacting to this with a ๐Ÿ‘

User Story

I have an image provided from a Gatsby source that Iโ€™d like to transform through imgix.

Description

This would allow developers to transform images that are provided from various Gatsby sources, such as Wordpress, via imgix. This prevents the image from needing to be downloaded to the developer's computer for processing. The image would also be served with our best-in-class global CDN.

feat: more debugging features

~/gatsby-project
cfaruki@website[imgix-gatsby !x] yarn start
yarn run v1.22.17
$ run-p start:**
$ yarn develop
$ yarn clean && gatsby develop --verbose
$ rimraf .cache public
verbose set gatsby_log_level: "verbose"
verbose set gatsby_executing_command: "develop"
verbose loading local command from: /Users/cfaruki/gatsby-project/node_modules/gatsby/dist/commands/develop.js
verbose running command: develop

verbose Transition to "initializing"
warn The following flag(s) found in your gatsby-config.js are not supported in your environment and will have no effect:
- DEV_SSR
info The following flags are active:
- FAST_DEV ยท Enable all experiments aimed at improving develop server start time.
- PRESERVE_FILE_DOWNLOAD_CACHE ยท (Umbrella Issue (https://gatsby.dev/cache-clearing-feedback)) ยท Don't delete the downloaded files cache when changing
gatsby-node.js & gatsby-config.js files.

There is one other flag available that you might be interested in:
- PARALLEL_SOURCING ยท EXPERIMENTAL ยท (Umbrella Issue (https://gatsby.dev/parallel-sourcing-feedback)) ยท Run all source plugins at the same time instead of
serially. For sites with multiple source plugins, this can speedup sourcing and transforming considerably.

success open and validate gatsby-configs, load plugins - 1.138s

 ERROR

(node:97162) [DEP0148] DeprecationWarning: Use of deprecated folder mapping "./public/" in the "exports" field module resolution of the package at
/Users/cfaruki/gatsby-project/node_modules/extract-files/package.json.
Update this package.json to use a subpath pattern like "./public/*".
(Use `node --trace-deprecation ...` to show where the warning was created)

info [@imgix/gatsby] Loaded plugin.
success onPreInit - 0.014s
success initialize cache - 0.076s
success copy gatsby files - 0.069s
verbose Attaching functions to development server
success Compiling Gatsby Functions - 0.240s
success onPreBootstrap - 0.252s
verbose Creating 5 worker
verbose Transition to "initializingData"
success createSchemaCustomization - 1.109s
verbose Transition to "initializingData" > "sourcingNodes"
verbose Checking for deleted pages
verbose Deleted 0 pages
verbose Found 0 changed pages
success Checking for changed pages - 0.003s
success source and transform nodes - 4.378s
verbose Transition to "initializingData" > "buildingSchema"
success building schema - 0.508s
verbose Transition to "initializingData" > "creatingPages"
success createPages - 0.135s
success createPagesStatefully - 0.158s
info Total nodes: 1069, SitePage nodes: 80 (use --verbose for breakdown)
verbose Number of node types: 10. Nodes per type: Directory: 38, File: 482, GraphQLSource: 1, ImageSharp: 272, Instagram: 6, MarkdownRemark: 158, Site: 1,
SiteBuildMetadata: 1, SitePage: 80, SitePlugin: 56
verbose Checking for deleted pages
verbose Deleted 0 pages
verbose Found 80 changed pages
success Checking for changed pages - 0.001s
verbose Transition to "initializingData" > "writingOutRedirects"
success write out redirect data - 0.003s
verbose Transition to "initializingData" > "done"
verbose Transition to "runningPostBootstrap"
success Build manifest and related icons - 0.118s
success onPostBootstrap - 0.121s
info bootstrap finished - 9.926s
verbose Transition to "runningQueries"
success onPreExtractQueries - 0.002s
success extract queries from components - 1.131s
verbose Transition to "runningQueries" > "waitingPendingQueries"
verbose Transition to "runningQueries" > "writingRequires"
success write out requires - 0.124s
verbose Transition to "runningQueries" > "calculatingDirtyQueries"
verbose Transition to "runningQueries" > "runningStaticQueries"
success run static queries - 0.282s - 10/10 35.51/s
verbose Transition to "runningQueries" > "runningPageQueries"
success run page queries - 0.014s - 2/2 141.85/s
verbose Transition to "runningQueries" > "waitingForJobs"
verbose Transition to "runningQueries" > "done"
verbose Transition to "startingDevServers"
verbose Attaching functions to development server

 ERROR

Error when resolving URL value for node type MarkdownRemarkFrontmatterMyCustomNode. This probably means that the getURL function in
gatsby-config.js is incorrectly set. Please read this project's README for detailed instructions on how to set this correctly.

Two things:

  1. The custom field configuration docs are not intuitive. Took me a couple hours of kicking the tires to figure out how it works.
  2. The above error only occurs at dev runtime. But there's no meaningful output. For projects at scale, this makes it frustratingly difficult to isolate the root cause of the graphql query failure. You should be able to see what part of the query failed.

Gatsby v4 compatibility

After upgrading to gatsby 4 and 1.7.0 of the imgix library (which adds gatsby 4 support), I get errors related to invalid config formats, though the format hasn't changed (and still seems to match the readme)

Steps to reproduce the behaviour:

  1. Have the following section in your fields config in gatsby-config.js:
fields: [
        {
          nodeType: "Instagram",
          fieldName: "image_imgix",
          getURL: (node) => node.image?.url
        },
        {
          nodeType: "ShopifyProductImages",
          fieldName: "imgix",
          getURL: (node) => node.url 
        },
      ],
  1. Build with production node env
  2. Error during "Validating Rendering Engines" of gatsby build:
error [@imgix/gatsby] Fatal error during setup: Error: The plugin config is not in the correct format. Errors: Invalid value [{"nodeType":"Instagram","fieldName":"image_imgix"},{"nodeType":"ShopifyProductImages","fieldName":"imgix"}] supplied to : GatsbySourceUrlOptions/fields: (undefined | Array<(({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))>)/0: undefined,Invalid value undefined supplied to : GatsbySourceUrlOptions/fields: (undefined | Array<(({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))>)/1: Array<(({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))>/0: (({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))/0: ({ nodeType: string, fieldName: string } & { getURL: Function })/1: { getURL: Function }/getURL: Function,Invalid value undefined supplied to : GatsbySourceUrlOptions/fields: (undefined | Array<(({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))>)/1: Array<(({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))>/0: (({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))/1: ({ nodeType: string, fieldName: string } & { getURLs: Function })/1: { getURLs: Function }/getURLs: Function,Invalid value undefined supplied to : GatsbySourceUrlOptions/fields: (undefined | Array<(({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))>)/1: Array<(({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))>/1: (({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))/0: ({ nodeType: string, fieldName: string } & { getURL: Function })/1: { getURL: Function }/getURL: Function,Invalid value undefined supplied to : GatsbySourceUrlOptions/fields: (undefined | Array<(({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))>)/1: Array<(({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))>/1: (({ nodeType: string, fieldName: string } & { getURL: Function }) | ({ nodeType: string, fieldName: string } & { getURLs: Function }))/1: ({ nodeType: string, fieldName: string } & { getURLs: Function })/1: { getURLs: Function }/getURLs: Function

Information:

  • imgix/gatsby version: [v1.7.0]

getGatsbyImageData() returns larger images than needed in scrSet

I am trying to constrain image width depending on screen sizes. On the largest screen the image is limited to 1040px width, on tablet it takes about 80% width and full width on mobile.

Even though I set breakpoints and maxWidth, the srcSet values from getGatsbyImageData() contains w units which results in loading 1280px wide image. Taking into account retina display, I expect the largest width to maybe appear as 2080px, but 1280px is useless in any of my cases.

Screenshot 2021-11-02 at 17 28 37

I've extracted my attempted code into a CodeSandbox.

Please advise, can I set width in pixels in srcSet for my breakpoints?

GraphQL types for imgixParams

This is a potential feature for this library. If you want to see us build this, please indicate your support by reacting to this with a ๐Ÿ‘

User Story

I want to have my imgix parameters in my Gatsby/GraphQL query be strongly-typed

Description

This would ensure that imgix parameters passed to any transformations in a GraphQL query would be strongly typed, to reduce errors, typos, and improve developer experience.

For example:

{
	allWordpressPosts {
		heroImage # The original image url
		imgixHeroImage( # The transformed hero image, served by imgix
			imgixParams: {
				auto: ["format", "compress", "not-a-parameter"], # this would throw an error as "not-a-parameter" is, well, not a valid paremeter.
				q: 50,
				focus: 10 # this would throw an error because focus is not an imgix parameter.
			}
		) {
			url
		}
}

Existing URL parameters are removed

Describe the bug

If a URL has existing URL parameters, such as rect for cropping, they are removed after the URL is transformed for url, fluid, fixed, and gatsbyImageData fields. Only parameters given to defaultImgixParams, the GraphQL field's arguments, and those produced by the library itself (such as during srcSet generation) are included.

To Reproduce

Provide a URL to the plugin with a rect parameter. Using buildFixedImageData as an example:

import { buildFixedImageData } from '@imgix/gatsby'

const url =
  'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?auto=compress,format&rect=0,1100,6091,1865&w=980&h=300'
const fixedImageData = buildFixedImageData(url, {
  w: 200,
  h: 100,
})

console.log(fixedImageData)

The following is logged:

{
  width: 200,
  height: 100,
  src: 'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined',
  srcSet: 'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined&dpr=1&q=75 1x,\n' +
    'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined&dpr=2&q=50 2x,\n' +
    'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined&dpr=3&q=35 3x,\n' +
    'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined&dpr=4&q=23 4x,\n' +
    'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined&dpr=5&q=20 5x',
  srcWebp: 'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined&fm=webp',
  srcSetWebp: 'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined&fm=webp&dpr=1&q=75 1x,\n' +
    'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined&fm=webp&dpr=2&q=50 2x,\n' +
    'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined&fm=webp&dpr=3&q=35 3x,\n' +
    'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined&fm=webp&dpr=4&q=23 4x,\n' +
    'https://images.prismic.io/gatsbygts-angelo/72d75488-437f-4e91-bb8a-4a03ef325714_patrick-robert-doyle-eb8dmXNOGP4-unsplash.jpg?ixlib=gatsbyTransformUrl-1.6.2&fit=crop&w=200&h=100&ar=undefined&fm=webp&dpr=5&q=20 5x'
}

Note the exclusion of ?auto=compress,format&rect=0,1100,6091,1865 in the URLs, which may be crucial to the image's representation.

Expected behaviour

The URL should include original parameters. Any parameters added by the plugin should be merged over the existing params.

Information:

  • imgix/gatsby version: 1.6.3

Additional context

I believe this is the behavior of @imgix/js-core's buildURL method. If the core JS library is to be left as is, could the Gatsby plugin automatically read the URL parameters and merge them into the top of the final params?

For example, the URL field config could add ...existingUrlParams above defaultParams here:

See: https://github.com/imgix/js-core/blob/e168e5da6874591f657ce6de95257fe5414a361c/src/index.js#L47-L60

Type Definition for "TRACED_SVG" Missing

Describe the bug

When using gatsby-plugin-image with Typescript, using placeholder: TRACED_SVG in the GraphQL query results in a type error.
Digging into this further, it appears that this file, graphqlTypes.ts is missing the attribute TRACED_SVG.

The full types can be found here: in gatsby-transformer-sharp. For some reason TRACED_SVG has been left out of the types definition for @imgix/gatsby. Is there a reason TRACED_SVG has been left out? It's a valid placeholder option, yet the current @imgix/gatsby library prevents its use.

To Reproduce
In a gatsby project configured with Typescript, create a GraphQL query which requests a TRACED_SVG placeholder.

  const data: MyGraphqlQuery = useStaticQuery(graphql`
    query MyGraphql {
      prismicFrontPage {
        data {
          image_resource_name {
            gatsbyImageData(placeholder: TRACED_SVG, layout: FULL_WIDTH)
          }
        }
      }
    }
  `);

Expected behaviour
This is a valid placeholder option, it is expected to have a type defined in this file, graphqlTypes.ts

Screenshots
image

Information:

  • imgix/gatsby version: "@imgix/gatsby@^1.6.9":
  • gatsby version: "gatsby": "^3.6.2",
  • gatsby-plugin-image version: "gatsby-plugin-image": "^1.6.0",

Unable to provide the right src to ImgixGatsbyImage and fetching images: error 403.

Before you submit:

Question

Hello, I am trying to make this library work on my project, but I have some issues.

I need to fetch images dinamically, so I followed what is suggested here.

  1. First of all I want to ask if you can define what is an "imgix-compatible URL".

It is important to note that this feature can only display images that are already on imgix or an imgix-compatible URL

  1. Could be what ever images Web Proxy can accept? So a URL to a public image can be good?

In your example of URL Transform Function there is this code:

 <ImgixGatsbyImage
  // Must be an imgix URL
   src="https://assets.imgix.net/amsterdam.jpg"
  ...
/>   
  1. So can I use only an imgix URL with ImgixGatsbyImage's component a not a imgix-compatible URL?

Also, I am not sure if I am providing the right src to the component. For instance, path to my public image with Web Proxy is https://example.com/path/to/image/image.jpg so if my domain on imgix is domain.imgix.net, url would be something like https://domain.imgix.net/https%3A%2F%2Fexample.com%2Fpath%2Fto%2Fimage%2Fimage.jpg. I need some cropping, width and height, so my final url would be https://domain.imgix.net/https%3A%2F%2Fexample.com%2Fpath%2Fto%2Fimage%2Fimage.jpg?fit=crop&max-w=600&max-h=600.

  1. What is the url I need to put on src of ImgixGatsbyImage?
  2. I need to include parameters (crop, width, height)?
  3. I need to include sign string?

ImgixGatsbyImage always encode src, so I do not think I need to put encoded url.

Digging into the API I find Object builders, and in particular buildGatsbyImageDataObject. With it I am able to succesfully query images and also display, but I have some questions about this solution:
7. Are there some drawbacks using this method instead of ImgixGatsbyImage?
8. I am using layout: 'constrained', width: 600 and height: 600, with max-w: 600, max-h: 600 and fit: crop, but images fetched are always 600x600 px. Is it expected?
9. In your example of buildGatsbyImageDataObject there is dimensions: { width: 5000, height: 3000 }. Is it required? Because without it I am receiving error in console.

I have a last question:
10. Can I use includeLibraryParam: false with buildGatsbyImageDataObject or ImgixGatsbyImage?

Thanks in advance for you answers!

Version 2.0.1 broken NPM package, missing dist/ folder

The package published on NPM for @imgix/[email protected] contains no dist folder and no node_modules. Build outputs referenced by gatsby*.js files and placed in /dist as part of the build are missing, breaking this plugin.

erikmuller@067-032 Downloads % npm pack @imgix/gatsby
npm notice 
npm notice ๐Ÿ“ฆ  @imgix/gatsby@2.0.1
npm notice === Tarball Contents === 
npm notice 29.9kB CHANGELOG.md                                                      
npm notice 1.3kB  LICENSE                                                           
npm notice 57.5kB README.md                                                         
npm notice 742B   fragments.js                                                      
npm notice 110B   gatsby-browser.js                                                 
npm notice 104B   gatsby-node.js                                                    
npm notice 102B   gatsby-ssr.js                                                     
npm notice 6.8kB  package.json                                                      
npm notice 1.8kB  src/api/fetchBase64Image.ts                                       
npm notice 1.3kB  src/api/fetchImgixMetadata.ts                                     
npm notice 966B   src/common/ar.ts                                                  
npm notice 1.9kB  src/common/cache.ts                                               
npm notice 32B    src/common/constants.ts                                           
npm notice 713B   src/common/createExternalHelper.ts                                
npm notice 1.1kB  src/common/fpTsUtils.ts                                           
npm notice 2.9kB  src/common/imgix-js-core-wrapper.ts                               
npm notice 1.8kB  src/common/ioTs.ts                                                
npm notice 374B   src/common/log.ts                                                 
npm notice 165B   src/common/number.ts                                              
npm notice 212B   src/common/tsUtils.ts                                             
npm notice 707B   src/common/uri.ts                                                 
npm notice 3.2kB  src/common/utils.ts                                               
npm notice 163B   src/gatsby-browser.ts                                             
npm notice 852B   src/gatsby-node.ts                                                
npm notice 179B   src/gatsby-ssr.ts                                                 
npm notice 89B    src/index.ts                                                      
npm notice 1.8kB  src/modules/gatsby-plugin/buildGatsbyImageDataBaseArgs.ts         
npm notice 1.3kB  src/modules/gatsby-plugin/createImgixBase64FieldConfig.ts         
npm notice 4.9kB  src/modules/gatsby-plugin/createImgixFixedFieldConfig.ts          
npm notice 5.0kB  src/modules/gatsby-plugin/createImgixFluidFieldConfig.ts          
npm notice 10.3kB src/modules/gatsby-plugin/createImgixGatsbyImageDataFieldConfig.ts
npm notice 2.0kB  src/modules/gatsby-plugin/createImgixUrlFieldConfig.ts            
npm notice 189B   src/modules/gatsby-plugin/fieldNames.ts                           
npm notice 10.1kB src/modules/gatsby-plugin/gatsby-node.ts                          
npm notice 4.9kB  src/modules/gatsby-plugin/graphqlTypes.ts                         
npm notice 43B    src/modules/gatsby-plugin/index.ts                                
npm notice 5.2kB  src/modules/gatsby-plugin/objectBuilders.ts                       
npm notice 1.6kB  src/modules/gatsby-plugin/privateTypes.ts                         
npm notice 1.6kB  src/modules/gatsby-plugin/resolveDimensions.ts                    
npm notice 3.9kB  src/modules/gatsby-plugin/typeBuilder.ts                          
npm notice 2.6kB  src/modules/gatsby-transform-url/breakpoints.ts                   
npm notice 763B   src/modules/gatsby-transform-url/common.ts                        
npm notice 7.3kB  src/modules/gatsby-transform-url/gatsbyPluginImage.ts             
npm notice 709B   src/modules/gatsby-transform-url/gatsbyPluginImageComponent.tsx   
npm notice 4.9kB  src/modules/gatsby-transform-url/index.ts                         
npm notice 356B   src/modules/gatsby-transform-url/types.ts                         
npm notice 1.6kB  src/pluginHelpers.browser.ts                                      
npm notice 731B   src/pluginHelpers.ts                                              
npm notice 2.9kB  src/publicTypes.ts                                                
npm notice 1.4kB  types/gatsby.d.ts                                                 
npm notice === Tarball Details === 
npm notice name:          @imgix/gatsby                           
npm notice version:       2.0.1                                   
npm notice filename:      @imgix/gatsby-2.0.1.tgz                 
npm notice package size:  46.9 kB                                 
npm notice unpacked size: 191.1 kB                                
npm notice shasum:        fe7bed80952427523ac5202cab408639876b77d0
npm notice integrity:     sha512-A8e46ht6X+b77[...]VoBkI/R3MUgvw==
npm notice total files:   50                                      
npm notice 
imgix-gatsby-2.0.1.tgz

On a side note, why does the package published on NPM include the /src and /types folders?

Is it possible to sign URLs when using the `getGatsbyImageData` hook?

I noticed the image URLs returned by the getGatsbyImageData hook are unsigned, causing issues when trying to render images from an Imgix source that has Secure URLs enabled. For example, attempting to pass the following in the image prop to GatsbyImage fails with a 403 error:

getGatsbyImageData({
  aspectRatio: 16/9,
  layout: "fullWidth",
  src: someImgixImageURL,
})

If secure URLs are disabled in the Imgix source, images are rendered without a hiccup. Additionally, the secureURLToken is configured correctly - images rendered with different integration methods throughout the site are being signed properly.

Is this a limitation of getGatsbyImageData (because it would otherwise expose the secure URL token to the browser) or is there something I'm missing?

Thanks in advance!

Unable to use focal point

Hi there

GraphQL does not allow hyphenated names. There are properties fpY, fpX but these just get passed to the generated URL and Imgix does not seem to know what to do with them. What am I doing wrong?

Why are fpX and fpY integers, shouldn't they be floats?

Thanks,
Richard

Gatsby V5 support - graphql dependency

Before you submit:

Describe the bug
After upgrading to Gatsby 5, which has a dependency on graphql 16, the plugin fails to load due to a dependency on version 15.

For reference, error when using v16 of graphql is TypeError: Class constructor GraphQLNonNull cannot be invoked without 'new'.

I'll try and work on this as a PR, but just to raise it incase there's already a reason it's not upto date.

To Reproduce
Install Gatsby v5, with the @imgix/gatsby plugin configured, fails during build with error above

Expected behaviour
Build passes as expected

fix: no support for `gatsby-plugin-image@3` so no `gatsby@5` support

With the recently introduced GatsbyJS v5 support the gatsby-plugin-image dependency hasn't been updated. This is relevant section of package.json:

  "peerDependencies": {
    "gatsby": "^2 || ^3 || ^4 || ^5",
    "gatsby-image": "^2 || ^3",
    "gatsby-plugin-image": "^1 || ^2"
  },

This invalidates GatsbyJS v5 support, because v5 requires gatsby-plugin-image to be v3.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.