Both AMD and CMD are browser side JS module specifications, the differences between the two are summarized as follows:
1, AMD advocates the reliance in front, CMD advocates the nearest dependence
/ / AMD: mod. Js define (['dependency1'.'dependency2'].function(require, exports, module){
//TODO
module.exports = {};
});
Copy the code
//CMD: mod.js
define(function(require, exports, module) {
var $ = require('jquery.js')
if(true) {
let a = require('./a.js');
//TODO
}
module.exports = {}
});
Copy the code
There are pros and cons to this distinction, only syntactic differences, and requireJS and SeaJS support each other
2, different execution timing: AMD is executed immediately after loading, CMD is delayed execution (the biggest difference between the two)
Executing immediately is easier to understand. Let’s look at the delayed execution of CMD. Again, take the code above as an example
//CMD: mod.js
define(function(require, exports, module) {
var $ = require('jquery.js')
if(true) {
let a = require('./a.js');
//TODO
} else{
let b = require('./b.js');
//TODO
}
module.exports = {}
});
Copy the code
Before executing mod.js, the module is parsed into strings, and then all dependencies in the module are found through regular expressions and loaded one by one, such as jquery.js, A.js and b.js in the example. However, loaded dependencies are not executed immediately, but only when JS executes into the require statement. For example, juery.js and a.js will be executed in order of execution, while b.js will never be executed because it is in the conditional else. It should be noted that the behavior of CMD to match dependencies in strings with regees can affect performance, which is also criticized by many.
3. Different methods to achieve on-demand loading
Both specifications implement on-demand loading, but implement different apis:
/ / AMD: define (function(require, exports, module){
document.getelementById('app').onclick = function() {
require(['myModule'].function (my){
my.printName();
});
}
//TODO
module.exports = {};
});
Copy the code
/ / CMD: define (function(require, exports, module){
document.getelementById('app').onclick = function() {
require.async('myModule'.function (my){
my.printName();
});
}
//TODO
module.exports = {};
});
Copy the code