Search code examples
javascriptmodulerequirejsamdcommonjs

In Javascript AMD, why is it useful to define a module without a name?


A named module makes sense for me:

define('myModule', ['dep1', 'dep2'], function (dep1, dep2) {

    //Define the module value by returning a value.
    return function () {};
});

When I want to use this module, I can use require to import it:

require('myModule', function(myModule){})

However, what I can't understand is the anonymous module like this (from requireJS examples):

define(['dep1', 'dep2'], function (dep1, dep2) {

    //Define the module value by returning a value.
    return function () {};
});

Is the code above used to define an anonymous module? If so, how can this module be used/imported/refered by other modules? Does anyone have ideas about this?


Solution

  • If you scroll down a bit on that page you linked, it says

    Notice that the above module does not declare a name for itself. This is what makes the module very portable. It allows a developer to place the module in a different path to give it a different ID/name. The AMD loader will give the module an ID based on how it is referenced by other scripts.

    So the module will in fact get a name, based on how you load the file that contains it.

    I guess the idea is that you develop with "anonymous" modules (one per file), and then have a build tool that bundles them all up (giving them names in the process).