Fixing Vite + Bootstrap + jQuery

Fixing Vite + Bootstrap + jQuery
Photo by Kenny Eliason / Unsplash

At some point within the version 9 release cycle, Laravel assets' bundling process has been migrated to Vite: yet another bundler introducing breaks and incompatibilities with many JS packages, just for the sake of the Javascript Fatigue.

Among the breaks introduced by Vite, the major one affecting my usual JS stack was about Bootstrap + jQuery. In fact, despite Bootstrap's website has some suggestion about dealing with Vite, still the jQuery interface to handle the built-in JS utilities (modals, popovers, tooltips...) did not work, and after some investigation I've found that the code intended to init the jQuery plugins fails to retrieve jQuery and just goes over. Perhaps Vite bundles Bootstrap and jQuery in the wrong order, perhaps the old jQuery misses to declare some ESM/AMD/WTF module identifier, perhaps I did not put some black magic in my Vite configuration file: I do not really know why that happened, so I started to look for a blind work-around.

The trick was to explicitely include that code in my own scripts, so to enforce execution:

import $ from 'jquery';
import * as bootstrap from 'bootstrap';

defineJQueryPlugin(plugin) {
  const name = plugin.NAME;
  const JQUERY_NO_CONFLICT = $.fn[name];
  $.fn[name] = plugin.jQueryInterface;
  $.fn[name].Constructor = plugin;
  $.fn[name].noConflict = () => {
    $.fn[name] = JQUERY_NO_CONFLICT;
    return plugin.jQueryInterface;
  }
}

defineJQueryPlugin(bootstrap.Modal);
defineJQueryPlugin(bootstrap.Tooltip);
defineJQueryPlugin(bootstrap.Popover);

Hard coding this behavior resulted in a correct initialization of the Bootstrap's interfaces, so I could use the formula $('.foobar').modal('show') as always.

For my own convenience I've moved this in jBob, my personal and strongly opinionated JS utilities library.