nuxt / image

Plug-and-play image optimization for Nuxt applications.
https://image.nuxt.com
MIT License
1.29k stars 257 forks source link

Add Shopify Provider #667

Open joshistoast opened 1 year ago

joshistoast commented 1 year ago

It would be very handy to have a Shopify Provider, they have a very flexible image cdn and lots of sizing and cropping options via the image image url.

michealroberts commented 8 months ago

@danielroe I'm going to attempt to tackle this, it looks like under the hood they are using Cloudflare, so we probably can extend that provider.

michealroberts commented 8 months ago

@joshistoast In the meantime, you might be able to extend the Cloudlfare provider, and override the base URL to Shopify's CDN: https://cdn.shopify.com/

michealroberts commented 8 months ago

@danielroe

Locally, this works really well for me:

import { joinURL, encodeQueryItem } from 'ufo'
import { type ProviderGetImage } from '@nuxt/image'
import { createOperationsGenerator } from '#image'

const shopifyBaseURL = 'https://cdn.shopify.com'

const operationsGenerator = createOperationsGenerator({
  keyMap: {
    width: 'w',
    height: 'h',
    dpr: 'dpr',
    fit: 'fit',
    gravity: 'g',
    quality: 'q',
    format: 'f',
    sharpen: 'sharpen'
  },
  valueMap: {
    fit: {
      cover: 'cover',
      contain: 'contain',
      fill: 'scale-down',
      outside: 'crop',
      inside: 'pad'
    },
    gravity: {
      auto: 'auto',
      side: 'side'
    }
  },
  joinWith: ',',
  formatter: (key, val) => encodeQueryItem(key, val)
})

const defaultModifiers = {}

// https://developers.cloudflare.com/images/image-resizing/url-format/
export const getImage: ProviderGetImage = (src, {
  modifiers = {},
  baseURL = shopifyBaseURL
} = {}) => {
  const mergeModifiers = { ...defaultModifiers, ...modifiers }
  const operations = operationsGenerator(mergeModifiers as any)

  // e.g., https://cdn.shopify.com/static/
  const url = operations ? joinURL(baseURL, src.replace(shopifyBaseURL, ''), operations) : joinURL(baseURL, src.replace(shopifyBaseURL, ''))

  return {
    url
  }
}

One thing I am confused about, is the baseURL property and where that comes from. Here, I set it to the Shopify CDN base URL, but is this the correct way to instantiate this?

I'm not sure why the baseURL is set to '/' for most providers, and is this necessary for Shopify?

manuelodelain commented 5 months ago

Here are all the available Shopify transformations https://cdn.shopify.com/

manuelodelain commented 5 months ago

Here is a more complete list (the format is missing from their demo) https://shopify.dev/docs/api/liquid/filters/image_url