I have read all the other posts I can find on this topic on Stack overflow (of which there are many). But from what I can gather, they all offer the same potential fixes such as wrapping the code with if(process.client)
, or wrapping the component with <client-only>
tags, and adding mode:"client"
or adding the client
suffix to the plugin in the nuxt.config.js
file. None of these solutions worked for me unfortunately. It seems that the package file (flickity.js) is still being run on the server side causing errors. I've tried replacing the import with a require and wrapping that in an if (process.client)
conditional as well, and that didn't work either.
The error I get if I do not include the import Flickity from 'flickity';
line is, as you can expect Flickity is undefined
. When I do include it as below, I get window is not defined - flickity.js
Does anyone know any other requirements to
prevent this package from running server side that I have missed?
Component which uses flickity (wrapped in a client-only tag)
<script>
import Flickity from 'flickity'; // I have tried removing this having been told that Nuxt automatically imports all plugins. But it didn't work and rendered a Flickity is undefined error
export default {
created() {
},
props: {
images: {
required:true,
type:Array
}
},
mounted() {
this.initiateCarousel();
},
methods: {
initiateCarousel() {
if (process.client) {
const gallery = this.$refs.gallery;
const carousel = this.$refs.carousel;
console.log(carousel)
var flkty = new Flickity( carousel , {
cellAlign: 'left',
lazyLoad: 3,
contain: true,
pageDots: false,
prevNextButtons: false
});
}
}
},
}
</script>
plugins array in nuxt.config.js
plugins: [
'~/plugins/flexboxgrid/index',
'~/plugins/flickity.client'
],
Flickity.client.js file in ~plugins directory
import Flickity from 'flickity';
(i also tried adding export default Flickity;
to this file but that rendered the same server errors
question from:
https://stackoverflow.com/questions/65833010/window-is-not-defined-error-in-nuxt-js-when-importing-a-non-vue-package-such-a 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…