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 usingrequireMethod that reads a file and executes, finally returning the internalexportsObject.
  • 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 functiondefine, it is a global variable.
  • define.amdIs followingAMDA special identifier of the specification, whose value isAn object.

CMD

  • This specification defines only one functiondefine, it is a global variable.
  • define.cmdIs followingCMDA 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.

  • UMDAMDCommon JSIn the mix.
  • AMDEvolve with browser-first principles, load modules asynchronously.
  • Common JSDeveloping on server first principles, choose synchronous loading and its modules do not need to be wrapped.
  • UMDCheck whether support is supportedNode.jsDoes the module of exports existNode.jsModule mode. Then decide whether to support it or notAMD(Define exists). If yes, useAMDMode 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?