Skip to content

Add automatic support for srcset and high res images #106

Description

@davestewart

Background

On higher resolution monitors it's nice to see higher resolution monitors.

Right now, you can use srcset in the markdown to achieve this:

![](image.png){srcset="image.png 640w, image@2x.png 1280w"}

However, it's a bit of a mouthful to write!

What would be cool would be at the scanning stage to identify @2x images and automatically generate srcset attributes which would be added to the AST so the page would automatically render high res images where they exist:

Markdown:

![An image](image.png)

Files:

image.png
image@2x.png

Results in:

<img
  src="image.png"
  width="640"
  height="320"
  srcset="image.png 640w, image@2x.png 1280w"
  sizes="(max-width: 640px) 100vw, 640px"
/>

Proposal

Config:

// nuxt.config.ts
export default defineNuxtConfig({
  contentAssets: {
    imageSize: 'attrs',

    srcset: {
      // naming pattern for retina variants
      // {name} = base filename, {ext} = extension, {scale} = multiplier
      pattern: '{name}@{scale}x.{ext}',

      // which scale multipliers to scan for
      scales: [2, 3],

      // auto-generate a sizes hint using the base image's intrinsic width
      // set to false to omit entirely
      sizes: '(max-width: {width}px) 100vw, {width}px',
    },
  }
})

At the image processing stage, if an image is found:

  • check for version scales
  • if found, build srcset of path and size
  • if supplied generate sizes string
  • assign properties to img in AST

The properties should look something like this:

sizes= '(max-width: 480px) 100vw, 480px'
srcset = [
  '/content/post/diagram.png 480w',
  '/content/post/diagram@2x.png 960w',
  '/content/post/diagram@3x.png 1440w',
]

Each srcset and sizes will be generated per image.

The final HTML will look something like this:

<img
  src="/content/post/diagram.png?width=480&height=300"
  width="480"
  height="300"
  srcset="/content/post/diagram.png 480w,
          /content/post/diagram@2x.png 960w,
          /content/post/diagram@3x.png 1440w"
  sizes="(max-width: 480px) 100vw, 480px"
>

Links

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions