Twilight Pony Inc. Twilight Pony Inc. - 6 months ago 3x
Javascript Question

jQuery source code uses Require.js, but the final file doesn't?

Uncompressed jQuery file:
jQuery Source code:

What are they doing to make it seem like the final output is not using Require.js under the hood? Require.js examples tells you to insert the entire library into your code to make it work standalone as a single file.

Almond.js, a smaller version of Require.js also tell you to insert itself into your code to have a standalone javascript file.

When minified, I don't care for extra bloat, it's only a few extra killobytes (for almond.js), but unminified is barely readable. I have to scroll all the way down, past almond.js code to see my application logic.


How can I make my code to be similar to jQuery, in which the final output does not look like a Frankenweenie?


Short answer:

You have to create your own custom build procedure.

Long answer

jQuery's build procedure works only because jQuery defines its modules according to a pattern that allows a convert function to transform the source into a distributed file that does not use define. If anyone wants to replicate what jQuery does, there's no shortcut: 1) the modules have to be designed according to a pattern which will allow stripping out the define calls, and 2) you have to have a custom conversion function. That's what jQuery does. The entire logic that combines the jQuery modules into one file is in build/tasks/build.js.

This file defines a custom configuration that it passes to r.js. The important option are:

  • out which is set to "dist/jquery.js". This is the single file produced by the optimization.

  • wrap.startFile which is set to "src/intro.js". This file will be prepended to dist/jquery.js.

  • wrap.endFile which is set to "src/outro.js". This file will be appended to dist/jquery.js.

  • onBuildWrite which is set to convert. This is a custom function.

The convert function is called every time r.js wants to output a module into the final output file. The output of that function is what r.js writes to the final file. It does the following:

  • If a module is from the var/ directory, the module will be transformed as follows. Let's take the case of src/var/toString.js:

        ], function( class2type ) {
        return class2type.toString;

    It will become:

    var toString = class2type.toString;
  • Otherwise, the define(...) call is replace with the contents of the callback passed to define, the final return statement is stripped and any assignments to exports are stripped.

I've omitted details that do not specifically pertain to your question.