mozjpeg-wasm
TypeScript icon, indicating that this package has built-in type declarations

0.2.138 • Public • Published

React Squoosh

React Squoosh is a library that allows you to resize and compress your images using WebAssembly in your React project. It was based on the amazing work done for Squoosh App.

Install

npm i react-squoosh

Hosting the wasm files

Download these two files and place them in your public folder:

The Gist

If you are using Create React App you can reference the wasm files using your public folder URL: process.env.PUBLIC_URL

import React, { useRef } from 'react';
import { useSquoosh, FitMethod } from 'react-squoosh';

const resizeWasmUrl = `${process.env.PUBLIC_URL}/squoosh_resize_bg.wasm`;
const optimizeWasmUrl = `${process.env.PUBLIC_URL}/mozjpeg_enc.wasm`;

const App = () => {
  const inputRef = useRef<HTMLInputElement>(null);
  const opts = {
    wasmFileUrls: { resizeWasmUrl, optimizeWasmUrl },
    resizeOpts: { width: 300, height: 300, fitMethod: FitMethod.Contain },
  };
  
  const { squooshFile, loading, imgSrcPreview, file } = useSquoosh(opts);
  
  const onChangeImage = () => {
    const files = inputRef.current?.files || [];
    if (files[0]) {
      squooshFile(files[0]);
    }
  };

  useEffect(() => {
    if (file) {
      // Do something with the compressed file
    }
  }, [file]);

  return (
    <div className="App">
      {loading ? <p>Loading...</p> : (
        <>
          <input
            ref={inputRef}
            accept="image/*"
            type="file"
            onChange={onChangeImage}
          />
          {imgSrcPreview && (
            <img src={imgSrcPreview}  alt="Preview" />
          )}
        </>
      )}
    </div>
  );
}

Package Sidebar

Install

npm i mozjpeg-wasm

Weekly Downloads

0

Version

0.2.138

License

Apache-2.0

Unpacked Size

54.2 kB

Total Files

20

Last publish

Collaborators

  • coredumped7893