How to Build a Custom Version of jQuery

Compiling a custom version of jQuery allows developers to reduce file size and optimize page load speeds by stripping out unused modules such as AJAX, effects, or deprecated APIs. By cloning the official jQuery source repository and utilizing npm along with its built-in Grunt tasks, you can generate a tailored distribution containing only the specific features required for your project.

Prerequisites

Ensure you have the following installed on your machine:

  • Node.js (LTS version recommended)
  • npm (included with Node.js)
  • Git

Step 1: Clone the jQuery Repository

Open your terminal and clone the official jQuery repository to your local machine, then navigate into the directory:

git clone https://github.com/jquery/jquery.git
cd jquery

To build a specific release rather than the current development branch, check out a tagged version (e.g., 3.7.1):

git checkout 3.7.1

Step 2: Install Dependencies

Install the project dependencies defined in package.json. This installs Grunt and the required build plugins locally:

npm install

Step 3: Identify Modules to Exclude

jQuery allows you to exclude several core modules using a leading minus sign (-). The most commonly excluded modules include:

  • ajax: Excludes all asynchronous HTTP request functionality.
  • ajax/xhr: Excludes XMLHttpRequest transport.
  • ajax/script: Excludes <script> tag transport.
  • ajax/jsonp: Excludes JSONP transport.
  • css: Excludes CSS manipulation methods.
  • deprecated: Excludes APIs scheduled for removal.
  • dimensions: Excludes width and height calculation methods.
  • effects: Excludes animations like .animate(), .fadeIn(), and .slideUp().
  • event: Excludes event handling methods.
  • event/alias: Excludes convenience event aliases like .click() or .hover().
  • offset: Excludes positional calculations like .offset() and .position().
  • wrap: Excludes DOM wrapping methods like .wrap().
  • exports/amd: Omits AMD registration for module loaders like RequireJS.

Step 4: Run the Custom Build Command

You can run the build task through npm or by invoking Grunt directly via npx.

Using npm:

Pass the exclusion flags to the build script after a double hyphen (--):

npm run build -- -ajax,-effects,-deprecated

Using Grunt directly:

Run the custom Grunt task followed by a colon and a comma-separated list of flags:

npx grunt custom:-ajax,-effects,-deprecated

Step 5: Retrieve the Compiled Files

Once the compilation task finishes, your custom build will be generated in the dist/ directory:

  • dist/jquery.js: The uncompressed, readable custom build.
  • dist/jquery.min.js: The minified and production-ready custom build.
  • dist/jquery.min.map: The sourcemap file for debugging.

You can now copy jquery.min.js directly into your web project.