⚠️

[Next.js] ライブラリーによる window is not defined エラーメモ

2024/01/31に公開

use clientのコンポーネント内でimportしているにもかかわらず window is not defined エラーがでる
解決: typeof window !== 'undefined'のときにだけimportする

  • before
import heic2any from 'heic2any'
  • after
if (typeof window !== 'undefined')
{
const heic2any = (await import('heic2any')).default
}

before

utils.ts
import heic2any from 'heic2any'

export const convertHEICToWebP = async (
  file: File,
): Promise<File> => {
  try {
    const convertedBlob = (await heic2any({
      blob: file,
      toType: 'image/webp',
      quality: 0.8,
    })) as Blob
    return await resizeImage(convertedBlob)
  } catch (error) {
    throw new Error('Conversion failed')
  }
}

after

utils.ts
export const convertHEICToWebP = async (
  file: File,
): Promise<File> => {
  if (typeof window !== 'undefined') {
    try {
      const heic2any = (await import('heic2any')).default
      
      const convertedBlob = (await heic2any({
        blob: file,
        toType: 'image/webp',
        quality: 0.8,
      })) as Blob
      return await resizeImage(convertedBlob)
    } catch (error) {
      throw new Error('Conversion failed')
    }
  } else {
    throw new Error(
      'Conversion failed: HEIC to WebP conversion must be run in a browser environment.'
    )
  }
}

Discussion