LoginSignup
4
2

More than 3 years have passed since last update.

【Nuxt.js】ReferenceError: window is not defined ってエラーが出た

Posted at

// この記事は、 note に投稿した記事の再掲です。

Nuxt.js だと SSR の影響で window とか document を使うとエラーが出るらしい。

// "ReferenceError: window is not defined" って言われる
window.addEventListener(scroll, myFunc);

回避方法が公式ドキュメントにあったのでメモ。

.vue ファイル内での処理

if (process.browser) {
  // ここに window とか document を使った処理
}

外部ライブラリを使う場合

.vue ファイル内

if (process.browser) {
  require('外部ライブラリのパス');
}

nuxt.config.js にも該当ライブラリを追加しておく

build: {
  vendor: ['外部ライブラリのパス']
}

参考

window または document が undefined のときは?
https://ja.nuxtjs.org/faq/window-document-undefined/

4
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
4
2