How to use heic2any in Next.js client side?

956 Views Asked by At

Have following code:

import convert from 'heic2any'

try {
    convertedImage = await convert({ blob: propsAndFile?.file })
} catch (error) {
    console.error(error)
}

But got this error, though they promise it will run on client side: https://www.npmjs.com/package/heic2any

info  - Collecting page data ..node:internal/process/promises:289
            triggerUncaughtException(err, true /* fromPromise */);
            ^

ReferenceError: window is not defined
    at /Users/janoskukoda/Workspace/tikex/portal/team/node_modules/heic2any/dist/heic2any.js:23:1
    at /Users/janoskukoda/Workspace/tikex/portal/team/node_modules/heic2any/dist/heic2any.js:11:26
    at Object.<anonymous> (/Users/janoskukoda/Workspace/tikex/portal/team/node_modules/heic2any/dist/heic2any.js:20:2)
    at Module._compile (node:internal/modules/cjs/loader:1205:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1259:10)
    at Module.load (node:internal/modules/cjs/loader:1068:32)
    at Module._load (node:internal/modules/cjs/loader:909:12)
    at Module.require (node:internal/modules/cjs/loader:1092:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at 2233 (/Users/janoskukoda/Workspace/tikex/portal/team/.next/server/pages/_app.js:176:18) {
  type: 'ReferenceError'
}

Node.js v19.1.0
1

There are 1 best solutions below

0
Xian Z On

First, I checked typeof window !== 'undefined' before the call, then I used require in the function, instead of importing at the top level.

if (typeof window !== 'undefined') {
      const heic2any = require('heic2any');
      await heic2any({
        blob: image,
        toType: 'image/jpeg',
        quality: 0.8 // Set the desired JPEG quality (0 to 1)
      }) // error check after//
}