DEV Community

dala00
dala00

Posted on • Originally published at crieit.net

2 1

Nuxt.jsでSSRかブラウザ上の処理かを判定する方法の一つ

Nuxt.jsで開発する場合、書いた処理がサーバーサイドレンダリング(SSR)時と、ブラウザ上での処理時の両方で実行される場合がある。それを判定したい時の方法。

正規の方法

正規の方法として、公式にも書かれているやり方。

window or document undefined?

こんな感じで判定できる。

if (process.browser) {
  require('external_library')
}
Enter fullscreen mode Exit fullscreen mode

TypeScriptの場合

ただし、TypeScriptの場合はprocessの型にbrowserというプロパティが無いため、エラーになってしまう。そのため色々あれこれ型をうまい事設定する方法も可能かもしれないが、とりあえず古式ゆかしい方法でも判定することができる。

    if (typeof window !== "undefined") {
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay