/vue-squoosh

Primary LanguageTypeScriptApache License 2.0Apache-2.0

Vue Squoosh

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

Install

npm i vue-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>
  );
}