How to Configure Babel for jQuery Projects
Configuring Babel in a jQuery project allows you to write modern ES6+ JavaScript while compiling your code into backwards-compatible syntax for older browsers. This guide provides a straightforward setup using Babel and Webpack, demonstrating how to install the required dependencies, create the configuration files, and expose jQuery globally to support both modern modules and traditional plugins.
Step 1: Initialize Your Project and Install Dependencies
To start, initialize a Node.js project if you haven't already, then install Babel, Webpack, and jQuery via npm.
npm init -y
npm install --save jquery
npm install --save-dev @babel/core @babel/preset-env babel-loader webpack webpack-cli@babel/core: The core Babel compiler.@babel/preset-env: A preset that automatically determines the Babel plugins needed based on your target browser environments.babel-loader: Enables Webpack to transpile JavaScript files using Babel.webpackandwebpack-cli: Bundles your scripts and handles dependencies.
Step 2: Configure Babel
Create a configuration file named .babelrc or
babel.config.json in the root directory of your
project:
{
"presets": [
[
"@babel/preset-env",
{
"targets": "> 0.25%, not dead"
}
]
]
}The targets option ensures code is compiled to support
active browsers with more than 0.25% market share.
Step 3: Configure Webpack with Babel Loader
Create a webpack.config.js file in your root directory.
This configuration connects Babel to your build process and uses
Webpack's ProvidePlugin to make jQuery accessible globally,
ensuring compatibility with legacy scripts and third-party jQuery
plugins.
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
],
mode: 'production',
};Step 4: Write Modern Code with jQuery
Create an entry file at src/index.js. You can now use
modern JavaScript features—such as arrow functions, template literals,
and async/await—alongside jQuery syntax:
import $ from 'jquery';
$(() => {
const message = 'Babel and jQuery are working together!';
const displayMessage = (text) => {
$('#app').html(`<h1>${text}</h1>`);
};
displayMessage(message);
});Step 5: Build the Project
Add a build script to your package.json:
"scripts": {
"build": "webpack"
}Run the build command:
npm run buildWebpack will process src/index.js, run it through Babel
to transpile your ES6+ syntax to ES5, bundle jQuery with your code, and
output the compiled result to dist/bundle.js. Include this
output script in your HTML file to run your application.