Nuxtjs with scrollmagic gives me "window is not defined"

Gregor Voinov picture Gregor Voinov · Dec 16, 2017 · Viewed 7k times · Source

I want to use scrollmagic with nuxtjs.

I installed scrollmagic via npm.

npm install scrollmagic

In my nuxt.config.js file i added

build: {
    vendor: ['scrollmagic']
},

And in my pages/index.vue file i simply imported it.

import ScrollMagic from 'scrollmagic'

But this results only in this error

[vue-router] Failed to resolve async component default: ReferenceError: window is not defined [vue-router] uncaught error during route navigation: ReferenceError: window is not defined at C:\pathto\node_modules\scrollmagic\scrollmagic\uncompressed\ScrollMagic.js:37:2 at C:\pathto\node_modules\scrollmagic\scrollmagic\uncompressed\ScrollMagic.js:22:20 at Object. (C:\pathto\node_modules\scrollmagic\scrollmagic\uncompressed\ScrollMagic.js:27:2)

How can i fix this?

Answer

Schwesi picture Schwesi · Dec 16, 2017

Add a file to your plugins folder called "scrollmagic.js" and paste the following code into it:

plugins/scrollmagic.js

import ScrollMagic from 'scrollmagic'

Add the plugin to your nuxt.config.js file

nuxt.config.js

module.exports = {
  build: {
    vendor: ['scrollmagic']
  },
  plugins: [
    // ssr: false to only include it on client-side
    { src: '~/plugins/scrollmagic.js', ssr: false }
  ]
}

Use it with if (process.client) {}

page or component

<script>
let scrollmagic
if (process.client) {
  scrollmagic = require('scrollmagic')
// use scrollmagic
}
</script>

For more information please consult the excellent documentation on this topic: https://nuxtjs.org/guide/plugins/