LoginSignup
7
2

More than 3 years have passed since last update.

gatsby.jsのbuild 時の'TypeError: Cannot read property 'split' of null'エラーの対処

Last updated at Posted at 2019-05-21

はじめに

gatsby.jsfirebaseでアプリを作成しているのですが、上記のエラーが生じ、「gatsby developではうまくいっているのにgatsby buildになるとうまくいかない、、、なぜだ、、、」となったので今後の為にメモ。

こちらのgithub issueがドンピシャで解決してくれたのでこちらを見ればOKだと思います。

対処方法

ざっくりbefore/after

before

const db = firebase.firestore();
const storage = firebase.storage();
const auth = firebase.auth();

after


let db, storage, auth;

if (typeof window !== 'undefined') {
    db = firebase.firestore();
    storage = firebase.storage();
    auth = firebase.auth();
}

何をしてるのか

読んでコードのごとく、windowオブジェクトの存在をチェックしてfirebaseの各種moduleを呼び出しています。なんでこんなことをするのか。

エラーの原因

gatsby.jsはbuildの際にNode.js環境でhtmlをレンダリングするようです。そのため、window objectが存在しません。なのでwindow objectを明示したコードを記述したりするとbuildがうまくいかなかったりします。

今回の場合はwindow objectを使用しているわけではないのですが、Node.js環境でfirebase.auth()を呼び出していることが原因でした。firebaseのclient side sdkはブラウザー環境で使用されることを前提としているため、Node.js環境はダメでしょ!ってなことみたいです。

gatsby build時のlogでwarning出してくれてました。

Warning: This is a browser-targeted Firebase bundle but it appears it is being 
run in a Node environment.

ちなみに、どこでsplit propertyが呼び出されていてエラーが生じているのかまでは深掘りしていません、、、、

参考

[v2] TypeError: Cannot read property 'split' of null when building #6668

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2