如何通过第三方脚本导入正确调用js模块

问题描述

我有一个非常奇怪的问题,我无法用手指指着。@H_404_1@

我正在使用Barba.js进行很棒的页面过渡,而使用Swiper.js则是可爱的轮播。问题在于它使您的页面成为SPA,因此您必须重新init脚本。告诉你真相很痛苦。@H_404_1@

在我的 barba.js 文件中,我在顶部叫一个旋转式旋转木马@H_404_1@

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();
    },}]
})

然后在我的 swiper.js 文件中@H_404_1@

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

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

  hs.init();
}

homeCarousel();

export { homeCarousel }

这一切正常但我还有另一个没有轮播的页面,因此.swiper-container将返回null。那也很好,但是因为要导入在barba.js的顶部@H_404_1@

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

刷新页面调用它,从而导致令人讨厌的错误@H_404_1@

Cannot read property 'push' of undefined @H_404_1@

cannot read property push of undefined error

@H_404_1@

更改路线后,不会出现可怕的控制台错误。@H_404_1@

我想在理想的世界中,我会将这个import语句放在if (document.querySelector('.swiper-container') != null)内,但是导入 have 是最高级的。@H_404_1@

有什么建议吗?我正要通过PC离开窗口。可能是一件好事。@H_404_1@

解决方法

在将swiper.js用作库时,它应仅包含没有副作用的API。 在这种情况下,请从homeCarousel();中删除swiper.js