Sometimes you don't need all of jQuery's modules. Officially, you can use their Grunt script to build a slimmed-down jQuery, but what if Webpack is more your thing? Enter this guide.
- From your project root, install jQuery as a dev dependency:
npm i -D jquery
or:
yarn add -D jquery
- Copy the bootstrap jquery.js file from node_modules to your source directory. Call it something like jquery.custom.js:
cp node_modules/jquery/src/jquery.js src/js/jquery.custom.js
- Edit your copy and do a search-and-replace of
./
to the relative path that resolves to jQuery'ssrc
directory from your directory. Example:./core
becomes../../node_modules/jquery/src/core
. - Comment out the modules you don't want. Be careful, there are some
gotchas. For example,
ajax/load
is the only module that directly loads theparseHTML
method, so don't comment it out if you need that. - In your Webpack config, use the
resolve.alias
option so that modules that load jQuery will load your custom script:
module.exports = {
...
resolve: {
alias: {
jquery: path.join(__dirname, 'src/js/jquery.custom.js')
}
}
...
};
- Compile away and enjoy a slimmer jQuery build!
I've tried this approach and it's working even better than using the official way (with grunt). I wonder why this approach isn't mentioned in other guides (at least in the jQuery docs). Thanks a lot for sharing!