Skip to content

Optimize images with Webpack and use picture HTML element #10467

Open
vasikarla-zz/create-react-app
#52
@sumanthratna

Description

@sumanthratna

Is your proposal related to a problem?

Our site http://hacktj.org/ loads lots of images, decreasing site performance. One solution would be lazy loading images using the attribute on the img element, but an even nicer solution would be to use the HTML picture element along with (optional) lazy loading.

Describe the solution you'd like

  1. at build-time, use Webpack to convert JPGs and PNGs to a variety of formats (perhaps make this opt-in somehow, to avoid long build times?)
  2. replace the single img with a picture (with optimized images and original as a fallback)
    • replacing HTML elements might not be possible with the current react-scripts
      • maybe InterpolateHtmlPlugin and other related plugins could be adapted to do this
      • or maybe users could use this for images:
import { OptimizedPicture } from "react-scripts";

const MyComponent = () => (
    <>
        <OptimizedPicture src="unoptimized.png" alt="A good alt." />
        <OptimizedPicture src="unoptimized-and-lazy.png" alt="Another good alt." loading="lazy" />
    </>
);

/* 
// instead of:
const MyComponent = () => (
    <>
        <img src="unoptimized.png" alt="A good alt." />
        <img src="unoptimized-and-lazy.png" alt="Another good alt." loading="lazy" />
    </>
);
*/

CRA should convert to the following filetypes:

  • JPEG 2000
  • JPEG XR
  • WebP

If loading="lazy" is passed to the image and width and height are not provided, CRA should automagically compute the dimensions of the image and pass those as width and height to avoid layout shift.

Describe alternatives you've considered

The current method to do this: Users could create a prebuild script to convert/optimizes images, and then manually write picture instead of img (and they could even create their own OptimizedPicture component). However, this results in a lot of repeat code across projects, which is why I think this should be in react-scripts.

Additional context

n/a

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions