RequireJS: Difference between "requirejs" and "require" functions RequireJS: Difference between "requirejs" and "require" functions javascript javascript

RequireJS: Difference between "requirejs" and "require" functions


They are exactly the same.

The reason is some environments might already have a require, in which case RequireJS doesn't overwrite it and allows usage of the library through requirejs

See this commit - https://github.com/jrburke/requirejs/commit/be45948433b053921dc6a6a57bf06d04e13b3b39


Are requirejs And require the Same?

As of RequireJS 2.1.15, require and requirejs in the global space are indeed "exactly the same", as can be evidenced by this test you can perform in the console:

> require === requirejstrue

That the test returns true tells you they are the exact same function object. They are not two functions that happen to have similar or identical code. They are the same object, period.

Note, however when you execute define(['require'], function (require) { The require passed to the function is normally different from the global require.

Should You Use require or requirejs?

It depends. RequireJS is an AMD loader but it is not the only loader in town. If you want to write code that conforms 100% to the AMD spec, so that someone using your code can use whatever loader they want without having to modify your code, then you should use require at the global level, because requirejs is specific to RequireJS. Another AMD loader won't define it. The AMD spec defines require but not requirejs.

If you are loading something else that defines a global require then you have to use requirejs at the global level to avoid conflict.

Inside a module, always use define to obtain a reference to require. You should do this quite irrespective of whether there is a conflict in the global space.


OK, they may indeed be "exactly the same". Let's then focus on why you would use one versus the other...

What is unclear is what should be considered "best practice": If requirejs provides extra assurance "if some environments might already have a require", then wouldn't it be a good idea to always use the requirejs function to define a require configuration rather than the require function?

Also, what happens if the unthinkable happens and the environment in question not only already has a "require" defined but also has a "requirejs" defined? Does that mean we should have a requirejsjs too? And so on...?