In RequireJS documents (http://requirejs.org/docs/api.html#modulename), I couldn't understand this sentence.
You can explicitly name modules yourself, but it makes the modules less portable
My question is
- Why explicitly naming module makes less portable?
- When explicitly naming module needed?
If you do not give the module a name explicitly, RequireJS is free to name it whichever way it wants, which gives you more freedom regarding the name you can use to refer to the module. Let's say you have a module the file
bar.js. You could give RequireJS this path:And you could load the module under the name
"foo". If you had given a name to the module in thedefinecall, then you'd be forced to use that name. An excellent example of this problem is with jQuery. It so happens that the jQuery developers have decided (for no good reason I can discern) to hardcode the module name"jquery"in the code of jQuery. Once in a while someone comes on SO complaining that their code won't work and theirpathshas this:This does not work because of the hardcoded name. The
pathsconfiguration has to use the name"jquery", all lower case. (Amapconfiguration can be used to map"jquery"to"jQuery".)It is needed when there is no other way to name the module. A good example is
r.jswhen it concatenates multiple modules together into one file. If the modules were not named during concatenation, there would be no way to refer to them. Sor.jsadds explicit names to all the modules it concatenates (unless you tell it not to do it or unless the module is already named).Sometimes I use explicit naming for what I call "glue" or "utility" modules. For instance, suppose that jQuery is already loaded through a
scriptelement before RequireJS but I also want my RequireJS modules to be able to require the modulejqueryto access jQuery rather than rely on the global$. If I ever want to run my code in a context where there is no global jQuery to get, then I don't have to modify it for this situation. I might have a main file like this:The
jquerymodule is there only to satisfy modules that need jQuery. There's nothing gained by putting it into a separate file, and to be referred to properly, it has to be named explicitly.