jQuery is a lightweight JavaScript library that makes DOM manipulation a breeze. Even with the rise of JavaScript frameworks such as React, Vue, and Agular, jQuery is still used in countless projects. jQuery can also be easily integrated into a modern JavaScript workflow such as Webpack. Let’s see how we can do that in this post.
Prerequisite:
The steps:
Including jQuery in your Webpack project is simple, just follow these steps
1. install jQuery:
$ npm i jquery
2. add these lines of code to your webpack.config.js
:
// webpack.config.js
module.exports = {
...
resolve: {
// import the unminified version of jQuery from the node_modules/ (which is preferable for webpack)
alias: {
jquery: "jquery/src/jquery"
}
}
...
// This is especially useful for legacy modules that rely on the presence of "$" or "jQuery" globally
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
};
3. import jQuery into your project
// in the main javascript file (e.g. main.js)
import 'jquery'; // refers to the "alias" form "webpack.config.js"
Conclusion:
With this simple setup, you can now use jQuery in your Webpack workflow as you do with any other npm package.