Common JS
- A single file is a module with its own scope. Variables, functions, and classes defined in one file are private and invisible to other files.
- Load the module using
require
Method that reads a file and executes, finally returning the internalexports
Object. - The order in which modules are loaded, in the order they appear in the code. Modules are loaded synchronously, so no further operations can be performed until they are loaded.
- Modules can be loaded multiple times, but only run once on the first load, and the results are cached and read directly from the cache when they are loaded later. For the module to run again, the cache must be cleared.
For example, Node.js is mainly used for server programming, and the loaded module files are generally stored in the local hard disk, so the loading is relatively fast, without considering the asynchronous loading mode, so the CommonJS specification is more suitable. However, in a browser environment, to load modules from the server, this must be done in asynchronous mode. Hence the AMD and CMD solutions.
AMD
- The asynchronous loading module specification so that modules and module dependencies can be loaded asynchronously. This matches the browser’s environment of asynchronously loading modules.
- This specification defines only one function
define
, it is a global variable. define.amd
Is followingAMD
A special identifier of the specification, whose value isAn object.
CMD
- This specification defines only one function
define
, it is a global variable. define.cmd
Is followingCMD
A special identifier of the specification, whose value isAn object.
if (typeof define === "function" && define.cmd) {
CMD module loaders such as sea-.js exist
}
Copy the code
UMD
UMD is intended to be a cross-platform solution.
UMD
是AMD
和Common JS
In the mix.AMD
Evolve with browser-first principles, load modules asynchronously.Common JS
Developing on server first principles, choose synchronous loading and its modules do not need to be wrapped.UMD
Check whether support is supportedNode.js
Does the module of exports existNode.js
Module mode. Then decide whether to support it or notAMD
(Define exists). If yes, useAMD
Mode to load modules.
(function(window, factory){
if(typeof exports === 'object') {// Common JS
module.exports = factory();
}else if(typeof define === 'function' && defined.amd){
/ / AMD
define(factory);
}else{
window.eventUtil = factory();
}
})(this.function(){
// module ...
})
Copy the code
extension
- Front-end modular development that bit of history
- How does sea-js work?