将SwiperJS与Browserify结合使用

Using SwiperJS with Browserify

本文关键字:结合 Browserify SwiperJS      更新时间:2023-09-26

我正在尝试在Browserify捆绑包中使用SwiperJS的jQuery插件。。。但是得到以下错误:

未捕获类型错误:$(…)。刷卡器不是的函数

我使用的精简(最小)代码如下:

'use strict';
global.$ = require('jquery');
require('./plugins/swiper.jquery.js');
$(function() {
    $('#hero').swiper();
});

在SwiperJS插件的底部,他们做:

if (typeof(module) !== 'undefined')
{
    module.exports = window.Swiper;
}
else if (typeof define === 'function' && define.amd) {
    define([], function () {
        'use strict';
        return window.Swiper;
    });
}

这似乎正确地设置了它的用途。

有人能帮我解释为什么会发生这种事吗?我相信可能是一些非常简单的事情。

经过多次努力,我决定尝试Vanilla JS版本的Swiper,而不是jQuery/Zepto端口。这样做修复了错误,Swiper也能正常工作。

配置有点不同,但最终看起来是这样的:

使用Swiper的我的英雄模块:

'use strict';
var cache = require('./cache.js'),
    swiper = require('../plugins/swiper.js');
function init() {
    if (cache.$hero.length) {
        var hero;
        hero = new swiper(cache.$hero, {
            autoplay: 2000,
            direction: 'horizontal',
            loop: true,
            speed: 700,
            grabCursor: true
        });
        console.info(hero);
    }
}
module.exports = function() {
    return init();
};

cache.$hero只是我的选择器,它来自我的cache模块——看起来像(以防你想知道这是怎么回事):

var cache = {
    $hero: $('#hero')
};

希望这最终能帮助到别人。不知道为什么jQuery版本不起作用。如有任何进一步的说明,我们将不胜感激。谢谢

您需要将插件公开给全局插件。我认为:)

 'use strict';
 global.$ = require('jquery');
 window.Swiper = require('./plugins/swiper.jquery.js');
 console.info(jQuery.fn.Swiper); //to test if the plugin has been loaded

我使用的是这样的idangero刷,没有问题:

require('./swiper.jquery.min.js');
var Swiper = require('./swiper.min.js');
var swiper = new Swiper('.swiper-container', {
    spaceBetween: 30,
    centeredSlides: true,
    autoplay: 5000,
    autoplayDisableOnInteraction: false,
    effect: 'fade',
    fade: { crossFade : true } 
});