How to Integrate jQuery with Webpack
Integrating jQuery into a modern JavaScript build system powered by
Webpack allows developers to use legacy libraries and modern modules
side by side. This guide explains how to install jQuery, import it as a
standard ES module, configure Webpack’s ProvidePlugin to
make $ available automatically across your project, and use
expose-loader to attach jQuery to the global
window object for legacy plugins.
Step 1: Install jQuery and Required Dependencies
Start by installing jQuery as a project dependency using npm or yarn.
npm install jqueryIf you plan to expose jQuery to legacy third-party plugins that
require a global window.$ or window.jQuery,
also install expose-loader as a development dependency:
npm install --save-dev expose-loaderStep 2: Use jQuery as a Standard ES Module
For modern codebases where you explicitly import dependencies, you do not need special Webpack configuration. Simply import jQuery in any JavaScript file where it is needed:
import $ from 'jquery';
$(document).ready(() => {
$('body').append('<h1>jQuery loaded via ES module!</h1>');
});Step 3: Automatically Provide jQuery Globally via ProvidePlugin
If you want jQuery to be available across all your files without
writing import $ from 'jquery' in every module, configure
Webpack’s built-in ProvidePlugin.
Open your webpack.config.js and add the following
configuration:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
}),
],
};Whenever Webpack encounters $, jQuery, or
window.jQuery inside your module code, it will
automatically import the jquery package behind the
scenes.
Step 4: Expose jQuery to the Global Window Object
Many legacy jQuery plugins expect window.$ and
window.jQuery to exist in the global browser environment
outside Webpack’s module wrapper. To bind jQuery to the actual
window object, configure expose-loader in
webpack.config.js:
module.exports = {
module: {
rules: [
{
test: require.resolve('jquery'),
loader: 'expose-loader',
options: {
exposes: ['$', 'jQuery'],
},
},
],
},
};Alternatively, you can manually attach it in your main entry file
(index.js):
import $ from 'jquery';
window.$ = $;
window.jQuery = $;Step 5: Handling Legacy jQuery Plugins
When using plugins that extend $.fn, import jQuery
first, then import the plugin:
import $ from 'jquery';
import 'bootstrap'; // If using a library that extends jQuery
import 'some-jquery-plugin';
$('#my-element').pluginMethod();Using ProvidePlugin combined with
expose-loader ensures full backward compatibility with
older jQuery ecosystems while retaining modern bundling
capabilities.