javascriptbootstrap-5webpack-encorebootstrap-carousel

Import Bootstrap & plugin Carousel with Webpack Encore


I'm working on a Symfony project with Webpack Encore and I have a problem with loading Bootstrap and the plugin Carousel.

It could come from the import of Bootstrap because it's seems to work (but not fully) when I import the file:

import './styles/bootstrap.min.css';

But the slider is not working at all when I import properly the package from 'node_modules':

import 'bootstrap';

And no error in the console. Here is my code :

app.css

@import '~bootstrap';
@import url('https://maps.googleapis.com/maps/api/js?language=en');
@import url('https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700');

app.js

//import './styles/bootstrap.min.css';
import 'bootstrap';

slider.js

import jQuery from 'jquery';

// make Carousel a jQuery plugin
import Carousel from 'bootstrap/js/dist/carousel';
import jQueryBridget from 'jquery-bridget';
jQueryBridget('carousel', Carousel, jQuery);

;(function ($, window, document, undefined) {
    $(document).ready(function () {
        $('.carousel').carousel({
            interval: 10000
        });
    });
})(jQuery, window, document);

Solution

  • First: try to understand what you're doing. While Webpack is used to compile JavaScript modules, jQuery is a library that has been developed when JS wasn't that modern. Nowadays, you might not need jQuery anymore. So you're combining modern JS with legacy JS. While it can work, don't try it if you don't need it.

    Bootstrap 5 doesn't need jQuery. So why use it? Take a look at the example from Bootstrap's own documentation:

    var myCarousel = document.querySelector('#myCarousel')
    var carousel = new bootstrap.Carousel(myCarousel, {
      interval: 2000,
      wrap: false
    })
    

    So this should be enough:

    var myCarousel = document.querySelector('.carousel')
    var carousel = new bootstrap.Carousel(myCarousel, {
      interval: 1000
    })
    

    Since you've had similar problems before, I really suggest to read the documentation of the libraries you want to use. Usually they provide good examples you can use.

    TL;DR: stop using jQuery and start reading documentation.