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

I am using requireJS 2.x. I found out that some tutorials (and the official docs) sometimes use

requirejs.config({ [...] });
requirejs(["module"]) ...

and sometimes

require.config({ [...] });
require(["module"]) ...

Is there any difference between those two functions (require and requirejs)? I could not find any word about that in the docs. :(

12434 次浏览

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

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...?

They are Same Open website which loaded require already

then open Chrome console

type require in console and press enter

type requirejs in console and press enter

you can find that they are same function with different names

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 === requirejs
true

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.