I know it's a really simple question, but I haven't seen any straightforward question/answer like it. I'm trying to decide if jQuery is worth keeping in my react app, and I am using it almost entirely for ajax. Is webpack smart enough to only include the ajax portions of jQuery in the bundle?
No, webpack will not only include the ajax portions of jquery in your bundle, even if you are using Webpack 2 (webpack 1 and previous does not implement tree-shaking; that is, the entire module will be included in your bundle, not just those that you import) this is because of how jquery is vended in NPM: as one, large jquery.js module.
If you are intent on using jquery, there are ways to build jquery using only the ajax module, but this will require some manual effort (eg. you can't just do import {ajax} from 'jquery'
). There is a babel plugin for lodash, which does vend each method in its own module so you don't have to include all of lodash in your webpack build. It is a babel plugin because it relies on the import { some_method } from 'library'
syntax.
If you are looking for an easy ajax library, I highly recommend using isomorphic-fetch (which, in browsers, just uses 'whatwg-fetch'). It keeps your code very tidy.
You can create your own version by following the documentation in the official jQuery repository here: https://github.com/jquery/jquery#how-to-build-your-own-jquery, but I have to say that I haven't been able to adapt those steps to my setup and also it involved using Grunt which is not part of our tool belt.
However I have found a very good Github Gist explaining how to do it only using Webpack: https://gist.github.com/rhaglennydd/abb2d27144e1a595e7c850b0a7611a21.
I think that a link only answer breaks some of the rules in SO, so I'm giving a short description.
npm install jquery
Copy the code from node_modules/jquery/src/jquery.js
to a file in your project (ex. code/resources/js/jquery
)
The imported files must be the original files in the node_modules
folder.
For example './core',
can become '../../../node_modules/jquery/src/core'
.
Remove or comment some modules: be sure to test that your code keeps working without raising errors.
This will tell Webpack to use your version whenever jquery
is needed in your code or in one of your dependencies.
For example:
module.exports = {
resolve: {
alias: {
jquery: `${environment.paths.source}/js/jquery-custom/jquery-custom.js`,
}
}
};
I have seen that if I remove a lot of modules the size will reduce, but if you don't it can even slightly increase: so this is a good strategy if you need to progressively remove some code or if you already use very little modules, otherwise you'd better stick to the original or find an alternative library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With