score:7

Accepted answer

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.

score:1

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.

1. install jquery throught npm

npm install jquery

2. copy the exported code

copy the code from node_modules/jquery/src/jquery.js to a file in your project (ex. code/resources/js/jquery)

3. edit the path to source files

the imported files must be the original files in the node_modules folder. for example './core', can become '../../../node_modules/jquery/src/core'.

4. remove the modules that you don't need

remove or comment some modules: be sure to test that your code keeps working without raising errors.

5. add your custom jquery as an alias in the webpack configuration

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`,
    }
  }
};

final word

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.


Related Query

More Query from same tag