How to use Bootstrap 4 and jQuery with Vite v2
Vite is a relatively new frontend build tool that’s significantly faster than Webpack. Have you been tempted to migrate an existing project using Bootstrap 4 to Vite, only to get stuck with this error message when running in development mode?
Uncaught ReferenceError: $ is not defined
at node_modules/bootstrap/js/dist/index.js (index.js:22)
at __require (chunk-3DB52H5I.js?v=a8788298:7)
at dep:bootstrap_js_dist_index:1
That was my situation last week, and in this post I’ll tell you how to get past the error message and get Bootstrap 4 working with Vite.
Why does this error happen?
Bootstrap expects jQuery to be available to it on the window
object, but it isn’t.
This is because jQuery when imported in an ESM context considers itself in non-global mode and therefore does not put
$
on window, but bootstrap is eagerly initialized on import and expects$
to be available on window.This is unfortunately a case where jQuery and Bootstrap were designed without ESM in mind so they rely on implicit global coupling to work.
— Evan You on the GitHub bug report
I tried adding jQuery to the window
object but that didn’t work.
Webpack worked around this with the ProvidePlugin
plugin. And we can do the same with Vite!
How to fix the jQuery error
1. Install a Rollup plugin
@rollup/plugin-inject performs the same function as the Webpack plugin. Let’s install it:
$ npm i --save-dev @rollup/plugin-inject
or
$ yarn add -D @rollup/plugin-inject
2. Edit the Vite config file
We now need to import and register the Rollup plugin. Open vite.config.js
and add the changes shown below. At a minimum this file will now look like:
import inject from '@rollup/plugin-inject';
export default {
plugins: [
// Add it first
inject({
$: 'jquery',
}),
// Other plugins...
],
// The rest of your configuration...
};
Now jQuery as $
will be available to the Bootstrap JS plugins that you import.
Enjoy the speed boost that Vite brings!