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?
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.
Off the top of my head, the only module I've seen that uses the named module method is jQuery. Personally, I would also recommend using the unnamed module pattern.
Named Modules
By naming a module, the name used to require is independent of its location. Another module author could blindly require 'jquery', without knowing the modules path. This is useful if you're developing a reusable module (outside of your project). However, it has the drawback that (using jQuery as an example), you would need to add and entry in the paths
config property for RequireJS to point to the correct location of the file. Otherwise RequireJS can't find the file to load, unless it is placed in your base require directory.
Unnamed Modules
I find these to be preferable because you can take advantage of relative require paths. Let's say you have two files modules/ClassA
and modules/ClassB
. ClassB
can require ClassA
using './ClassA'
, and the entire directory can be moved if needed. By using an unnamed module, you also eliminate the possibility of a naming collision, unless you manage to find a way to place two files in the same directory, with the same name.