如何使用来自第三方脚本的导入正确调用 js 模块

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

我有一个非常奇怪的问题,我无法解决。

我正在使用 Barba.js which makes awesome page transitions and Swiper.js,这是一个可爱的旋转木马。问题是它使您的页面成为 SPA,因此您必须重新 init 脚本。说实话很痛苦。

在我的 barba.js 文件中,我在顶部调用了滑动器轮播

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文件中

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

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

  hs.init();
}

homeCarousel();

export { homeCarousel }

这一切都有效 o.k。但我有另一个页面没有旋转木马,所以 .swiper-container 将 return 为空。这也很好,但是因为我在 barba.js

的顶部导入
import { homeCarousel } from './swiper.js'

刷新页面时调用它,从而导致严重错误

Cannot read property 'push' of undefined

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

我想在一个理想的世界中,我会把这个导入语句放在 if (document.querySelector('.swiper-container') != null) 中,但是导入 have 是顶级的。

有什么建议吗?我即将通过 PC 退出 window。应该是好事吧。

当您使用 swiper.js 作为一个库时,它应该只包含 API 而没有副作用。 在这种情况下,从 swiper.js.

中删除 homeCarousel();