Simple rough understanding of Commonjs, AMD, cmd

Source: Internet
Author: User
Tags i18n locale vars

For large Web applications or projects, tens of thousands of lines of code, to develop and post-maintenance has brought great trouble. Therefore, a standardized module management mechanism is needed to help developers centralize the definition and invocation relationships of the modules.

Before the official launch of ES6, there have been a number of people committed to the introduction of web development for the modular management standards, CommonJS, AMD and CMD is one of the successful representatives.

The following is the most intuitive understanding of the three after I have consulted the information:

CommonJS

Typically applied to the server, the implementation is represented by: NodeJS. Nodejs believe that everyone is not unfamiliar, it has been successful in the application of JavaScript to the server side, so that the former developers can be more effort to turn to the backend development, without learning a new language.

On the server side, the load and execution of the module is done locally, so COMMONJS does not require the asynchronous loading of the module.

module definition and loading
    • For Commonjs, the module exists as a file, and the module implementation is all inside the file
    • At the end of the file, you need to add the method you want to export to the Module.exports object
    • Later in other files (modules), you can use the Require () method to load the required module, which requires a parameter: It can be a module name (which is now loaded by default), or a URL. If it is a URL, it can be a relative path or an absolute path, or a specified path (parsed and looked up by node itself). The suffix name of the file, the default is ". js", so the parameter can omit the suffix name, and if the specified module is not found, will continue to look for ". JSON" and ". Node" suffix files (where the ". Node" suffix of the file will be in the compiled binary file format parsing).
Amd

AMD (asynchronous module loading) and cmd are commonly used in the browser side, the most obvious difference between them and Commonjs is asynchronous loading. AMD's implementation represents Require.js, which is also an additional product of require.js in the promotion process.

module definition and loading
  • AMD modules are not necessarily file-based, small module clusters are also allowed, but basically in the development process, should be managed in the form of files
  • The definition of a module is determined by the define () method, which accepts two parameters:
    • One is the dependent module of the current module, passed in an array form
    • The second is the implementation of the current module, which is passed in callback form. One of the dependencies is passed to the callback via parameters. At the end of the callback, the method group that needs to be exposed is returned as an object.
  • The configuration of the module uses the Require.config () method, which takes a parameter of an object type that needs to be configured with some properties: Baseurl,paths,shim, etc.
    • BASEURL: The root path of all module lookups; default is the directory in which the HTML file using Require.js is located, if not set. Alternatively, you can use the Data-main property to define the root path in the tag that loads the require.js.
    • Callback: A callback function that currently relies on full load completion
    • Config: used when application level configuration information is passed to the module. Use the Module.config () method when passing.
      Requirejs.config ({config: {' bar ': {size: ' large '}, ' Baz ': {color: ' Blue '}}}    );  Bar.js directly using module modules define (function (require, exports, module) {    var size = Module.config ( ). Size;}); // Baz.js uses a dependent array, and requires a special dependent "module" function (module) {    var color = module.config (). color;});

      When "Some/newmodule" calls "Require (' foo ')", it gets to the Foo1.2.js file, and when "some/oldmodule" calls "' Require (' foo ')" It gets to foo1.0.js.

    • Exports: output of the module
    • Init: Initialization of the module works
    • Paths: The path to the module file. When the paths in/begins, or ends with. js, or contains a protocol (such as http://...). ) whose path is not under the root path.
    • Shim: Used when modules that are not defined with the Define () method are required. The value is a set of module objects, each of which has properties: Deps,exports,init, and so on. It is important to note that shim only defines the dependencies of the modules and still needs to be called by Define+require.
      • Deps: dependent array of modules
      • Exports: output of the module
    • Map: For a given module prefix, use a different module ID to load the module. You can use the * number as the default configuration, and the configuration can be overridden by a more specific configuration.
      Requirejs.config {map: {'    some/newmodule ': {        ' foo ': ' foo1.2 '    },    ' Some/oldmodule ': {        ' foo ': ' foo1.0 '}}    );
    • More parameters please poke reference link
Cmd

CMD (Universal module loading) is the output of sea.js in the promotion process, and it has the following differences with AMD (official description from SEAJS):

    • There are differences in positioning. Requirejs want to be a browser-side module loader, and also want to be a module loader for Rhino/node and other environments. Sea.js is focused on the Web browser side, and the node extension makes it easy to run in the node environment.
    • The specifications that follow are different. Requirejs follows the AMD (asynchronous module definition) specification and Sea.js follows the CMD (Universal module definition) specification. The differences between the specifications lead to different APIs. Sea.js is closer to CommonJS modules/1.1 and Node Modules specifications.
    • The concept of promotion is different. Requirejs is trying to get a third-party class library to modify itself to support Requirejs, and only a handful of communities have adopted it. Sea.js not strong push, adopt the way of self-encapsulation to "Haina hundred Rivers", now has the more mature encapsulation strategy.
    • There are differences in support for development debugging. Sea.js is very concerned about the development and debugging of code, there are NoCache, debug, etc. for debugging plug-ins. Requirejs no obvious support in this regard.
    • Plug-in mechanism is different. Requirejs takes the form of a reserved interface in the source code, the plug-in type is relatively single. Sea.js is a generic event mechanism that has a richer plug-in type.
    • AMD advocates a dependency on the predecessor, which is the definition of loading at the outset. CMD, however, is highly dependent on the nearest, relying on loading the code before it is used to the module. It is important to note that the use of Requirejs is loaded in the order in which the modules are dependent, i.e. the modules are not loaded in the order of the Code and may result in unexpected results.

      This creates two distinct ways of loading: "Preload" and "lazy loading." AMD starts executing the main process after loading all the dependencies of all modules in advance, and Cmd is encountering a dependency starting load, executing the current process after completion, encountering the next dependency to load again, and then performing the next step. Of course, the dependencies between the same modules are still loaded asynchronously.

module definition and loading

The process is similar to AMD and is no longer mentioned, but simply introduces the Seajs API.

  • Cache: View module information in the current module system
  • Config: Configure module parameters, parameter list:
    • Alias: module Alias
    • Base: Root Path
    • Paths: The path of the module file
    • VARs: Variable configuration. For example, you need to determine the module path at run time:
      seajs.config ({    //  variable configuration     vars: {        ' locale ': ' ZH-CN '    }}); Define (function(require, exports, module) {  var lang = require ('./i18n/{ Locale}.js ');      // = = loaded with Path/to/i18n/zh-cn.js});

      The use of variables needs to be surrounded by curly braces, as in the example {locale}.

  • Data: View the values of all SEAJS configurations and some internal variables that can be used for plug-in development. It can also be used for debugging when the load encounters a problem.
  • Resolve: Using the internal mechanism of the module system to parse the incoming string parameters.
  • Use: Loads the module. Seajs.use (Id/url/urlarray, callback)

Simple and rude understanding of Commonjs, AMD, cmd

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.