javascriptbarbajs

How to correctly call js modules with imports from third party scripts


I have a very strange problem I can't put my finger on.

I am using Barba.js which makes awesome page transitions and Swiper.js which is a lovely carousel. The problem is that it makes your page a SPA so you have to reinit scripts. Quite a pain to tell you the truth.

In my barba.js file I call a swiper carousel at the top

import barba from "@barba/core";    
import { homeCarousel } from './swiper.js'

function initCarousel() {
if (document.querySelector('.swiper-container') != null) {
    homeCarousel();
  }
}

barba.init({
  sync: true,
  preventRunning: true,
  views: [{
    namespace: 'main',
    afterEnter() {
      setTimeout(() => {
        initCarousel();
      }, 550);
    }
  }],
  transitions: [{
    async leave() {
      done();
    },

    async enter() {
      newPage();
    },
  }]
})

Then in my swiper.js file

import Swiper from 'swiper';
import 'swiper/css/swiper.css';

const homeCarousel = () => {
  var hs = new Swiper('.home__carousel', {
    init: false,
  });

  hs.init();
}

homeCarousel();

export { homeCarousel }

This all works o.k. but I have another page that doesn't have a carousel on it so .swiper-container will return null. That's good too, but because am importing at the top of barba.js

import { homeCarousel } from './swiper.js'

It's called when the page is refreshed thus causing a nasty error

Cannot read property 'push' of undefined

cannot read property push of undefined error

When the route is changed, there's no horrible console error.

I guess in an ideal world I would place this import statement inside of the if (document.querySelector('.swiper-container') != null) but imports have to be top level.

Any suggestions, please? I'm about to through the PC out of the window. Probably a good thing.


Solution

  • As you use swiper.js as a library it should contain only API without side effects. In this case remove homeCarousel(); from swiper.js.