I have seen people use an alternate define “syntax” in require js than what is described in the require js’ documentation, or in many tutorials.
The usual define “syntax”:
define(['module/first'], function (firstModule) {
//Module code with a dependency on module/first goes here.
});
The alternate define “syntax”:
<script data-main="app/config" src="assets/js/libs/require.js"></script>
file: config.js:
require.config({
paths: {
jquery: '../assets/js/libs/jquery'
}
});
require(['app']);
file: app.js:
define(function(require) {
var FirstModule = require('modules/first');
//Module code with a dependency on module/first goes here.
What are the advantages, and disadvantages of using this alternate “syntax”?
I think your explanation is a bit misleading: in both cases, you will have a top-level
requirecall with adata-mainattribute specifying a file to kick-start the process of requiring different modules.So typically you will have this in your HTML:
Then, in both cases, you would have a file
app/configwhich sets your configuration (although you could do this directly in the HTML) and more importantly callsrequireon your modules:Now, it’s when we get to defining modules with dependencies that these styles differ. In the amd style you pass in the module names (paths) as an array, and a function which takes the same number of arguments:
app.js
In the simplified CommonJS syntax, you just pass
requireintodefineand then require whatever modules you need inline:app.js
Getting back to your original question, the advantages of the CommonJS style over the amd style should be clear.
For one thing, with the conventional syntax, if there are many modules being required, it is very easy to mistakenly assign modules to the wrong variable names. Consider this common case:
Right away, you can see that when we add a new module to this list, we have to be very careful that the corresponding new function argument appears in the right place, or else we can have jQuery assigned to
Backbone, etc. In some cases this can create very subtle bugs that are hard to track down.Now consider the CommonJS syntax:
Note that:
Those are just a few reasons that come to mind, I’m sure there are others. Basically, if you just have one or two dependencies, either syntax will do fine. But if you have a complex network of module dependencies, the CommonJS syntax is probably preferable.
Note that in the RequireJS docs, they mention this small caveat:
But this is not a major issue: