Search code examples
javascriptnext.jsimportimage-compression

Image compressor not importing in nextjs


I am trying to compress an image but when i try to import image compress normally like this:

import ImageCompressor from "image-compressor.js";

It gives error:

Uncaught ReferenceError: window is not defined

This is my code:

              const handleImage = async (e) => {
                const selectedFile = e.target.files[0];
                if (selectedFile) {
                    try {
                        const compressedDataURL = await compressImage(selectedFile);

                        console.log("Compressed dataURL: ", compressedDataURL);

                        setImage(compressedDataURL);
                    } catch (error) {
                        console.error("Error compressing image:", error);
                    }
                }
            };
            //Compressing images function
            const compressImage = async (file) => {
                return new Promise((resolve, reject) => {
                    new ImageCompressor(file, {
                        quality: 0.5, // Adjust the quality as needed
                        success(result) {
                            const reader = new FileReader();
                            reader.onload = (e) => {
                                const imageData = e.target.result;
                                resolve(`data:image/jpeg;base64,${btoa(imageData)}`);
                            };
                            reader.readAsBinaryString(result);
                        },
                        error(e) {
                            reject(e);
                        },
                    });
                });
            };

another way i tried was importing image compressor inside the compressing function :

const compressImage = async (file) => {
try {
    // Import the ImageCompressor class from the library
    const { ImageCompressor } = await import("image-compressor.js");

    return new Promise((resolve, reject) => {
        new ImageCompressor(file, {
            quality: 0.5, // Adjust the quality as needed
            success(result) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    const imageData = e.target.result;
                    resolve(`data:image/jpeg;base64,${btoa(imageData)}`);
                };
                reader.readAsBinaryString(result);
            },
            error(e) {
                reject(e);
            },
        });
    });
} catch (error) {
    console.error("Error importing ImageCompressor:", error);
   }
  };

But it just gave error that it cant be a state variable


Solution

  • Use a useEffect to import your image compressor, like this:

             useEffect(() => {
                // Dynamically load ImageCompressor if needed (e.g., in the browser)
                if (typeof window !== "undefined") {
                 import("image-compressor.js").then((module) => {
                     // Store it in the window object for later use
                    window.ImageCompressor = module.default || module;
                });
            }
           }, []);