#StackBounty: #javascript #ecmascript-6 #react.js Working with images in multiple formats

Bounty: 50

I’ve been doing some research around how to best make use of the WebP images (with fallback) in React. Most solutions point to something similar to what I’ve written below. That means if I have a lot of images I have to export the same image twice in assets.js (both PNG and WebP), import twice and provide two Image props for the same image.

This feels very inefficient. Is this an uncommon way of working with images? Is there a better way for working with images that live locally?

assets.js – where I collect all my assets and export them as strings. Imagine this list being really lengthy.

export { default as image1 } from "./assets/image-1.png";
export { default as image1Webp } from "./assets/image-1.webp";

In the file I import the assets I need for that page

import {
} from "./assets";

The component + props


Image.js component

const Image = ({
  type = 'image/webp',
}) => {
  return (
      <source srcSet={src} type={type} />
      <img src={fallback} {...delegated} />

Some things I’ve tried:

Generally the recommended way is to add images to a React project is to use require(img/path). So I tried things like appending .png or .webp to the base URL, inside the Image component. so I only need to define one string and then the component handles the splitting.

e.g. pseudocode:

export const toWEBP = (src) => {
  const location = src.split(".")
  return `${location}.webp`

Get this bounty!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.