Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SwiperJS with Browserify

I am trying to use the jQuery plugin of SwiperJS in my Browserify bundle...but get the following error:

Uncaught TypeError: $(...).swiper is not a function

The stripped down (bear minimal) code I am using is as follows:

'use strict';

global.$ = require('jquery');
require('./plugins/swiper.jquery.js');

$(function() {
    $('#hero').swiper();
});

At the bottom of the SwiperJS plugin they do:

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

Which seems to correctly set it up for this use.

Can anybody help me with why this is happening? Probably something very simple I'm sure.

like image 853
Michael Giovanni Pumo Avatar asked May 01 '26 09:05

Michael Giovanni Pumo


1 Answers

After much hair pulling, I decided to try the Vanilla JS version of Swiper, as opposed to the jQuery / Zepto port. Doing so fixed the errors and the Swiper works.

Configuration was a little different but ended up looking like this:

My Hero Module that uses 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 is simply my selector that comes from my cache module - looking something like (just in case you were wondering what that was about):

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

Hope this ends up helping someone. No idea why the jQuery version didn't work. Any further light on that would be appreciated. Thanks!

like image 64
Michael Giovanni Pumo Avatar answered May 03 '26 22:05

Michael Giovanni Pumo