Named module vs Unnamed module in RequireJS

Aniket picture Aniket · Nov 1, 2013 · Viewed 12.2k times · Source

We can create a module in requireJS by giving it a name:

define("name",[dep],function(dep) {
      // module definition
});

or we can create one excluding the name:

define([dep],function(dep) {
      // module definition
});

Which is the better way to create a module? I know RequireJS recommends to avoid assigning module names.

But I want to know in what scenarios we do and do not have to give a module a name. Does this affect usage? What are the pros and cons of each way?

Answer

Louis picture Louis · Nov 1, 2013

This is what the requirejs documentation says on the topic of named modules:

These are normally generated by the optimization tool. You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name. It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names. The optimization tool needs to add the names so that more than one module can be bundled in a file, to allow for faster loading in the browser.

But let's say you want your module to have a single well-known name that allows always requiring it in the same way from any other module. Do you then need to use the define call with a name? Not at all. You can use paths in your configuration:

paths: {
   'jquery': 'external/jquery-1.9.1',
   'bootstrap': 'external/bootstrap/js/bootstrap.min',
   'log4javascript': 'external/log4javascript',
   'jquery.bootstrap-growl': 'external/jquery.bootstrap-growl',
   'font-awesome': 'external/font-awesome'
},

With this configuration, jQuery can be required as "jquery", Twitter Bootstrap as "bootstrap", etc. The best practice is to leave calling define with a name to the optimizer.