GatsbyJSで "WebpackError: ReferenceError: IDBIndex is not defined"とエラーが出た場合の対処方法

GatsbyJSで gatsby buildコマンド実行時に「WebpackError: ReferenceError: IDBIndex is not defined」とエラーが出たのでその対応方法のメモ。

具体的にはFirebaseを読み込んでいる以下のようなコードでエラーが発生しました。

import firebase from "firebase"
 
const config = {
  apiKey: "xxx",
  authDomain: "xxx",
  databaseURL: "xxx",
  projectId: "xxx",
  storageBucket: "xxx",
  messagingSenderId: "xxx",
  appId: "xxx",
}
 
firebase.initializeApp(config)
 
export const functions = firebase.functions()

importしているサードパティーのライブラリがwindowオブジェクトなどにアクセスしている場合に発生するらしいです。

これは以下のようにrequireを利用してwindowオブジェクトがある場合にのみ読み込むようにすることで対応することができます。

let _functions
if (typeof window !== "undefined") {
  const firebase = require("firebase")
  
  const config = {
    apiKey: "xxx",
    authDomain: "xxx",
    databaseURL: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
    messagingSenderId: "xxx",
    appId: "xxx",
  }
 
  firebase.initializeApp(config)
  _functions = firebase.functions()
}
 
export const functions = _functions

参考: Debugging HTML Builds | GatsbyJS

スポンサードリンク

«React.lazyを利用してJavaScriptファイルを分割ロード | メイン | TypeScriptのインデックス シグネチャでオブジェクトのキーの型を指定する»