CMD (sea.js) module definition specification

Source: Internet
Author: User

CMD Module Definition Specification

In Sea.js, all JavaScript modules follow the CMD (Common module definition) module definition specification. This specification clarifies the basic writing format and basic interaction rules of the module.

In the CMD specification, a module is a file. The code is written in the following format:

Define (factory);

Define Function

defineis a global function used to define the module.

Define define(factory)

defineAccepts a factory parameter, either factory as a function or as an object or as a string.

factoryAs an object, a string, the interface that represents the module is the object, the string. For example, you can define a JSON data module as follows:

Define ({"foo": "Bar"});

Template modules can also be defined by a string:

Define (' I am a template. My name is {{name}}. ');

factoryAs a function, the representation is the construction method of the module. By executing this construction method, you can get the interface that the module provides to the outside. factorywhen the method executes, the default is to pass in three parameters: require ,, exports and module :

Define (function(require, exports, module) {  //  Modules code });

Define define(id?, deps?, factory)

defineYou can also accept more than two parameters. idthe string represents the module identity, and the array deps is module dependent. Like what:

function (Require, exports, module) {  //  Modules code });

idand deps parameters can be omitted. When omitted, it can be generated automatically through the build tool.

Note : id deps The use of bands and parameters define is not part of the CMD specification, but belongs to the Modules/transport specification.

Define.cmd Object

An empty object that can be used to determine if the current page has a CMD module loader:

if (typeof define = = = "function" && define.cmd  ) {//  have sea.js etc cmd module loader Exist
}

can be used to introduce other libraries

Exposing jquery

if (typeof define = = = "function" && define.cmd) {    define (function(Require, Exports,module) {        = jQuery;    })}

Require Function

requireIs factory the first parameter of a function.

Require require(id)

requireis a method that accepts a module identity as a unique parameter that is used to obtain the interfaces provided by other modules.

Define (function(require, exports) {  //  get module A's interface  var a = require ('./a ')  ; // method of calling module a   a.dosomething ();});

Note : At development time, require the writing needs to follow some simple conventions.

Require.async require.async(id, callback?)

require.asyncmethod is used to load the module asynchronously inside the module and execute the specified callback after the load completes. callbackparameters are optional.

Define (function(require, exports, module) {  //  asynchronously loads a module and executes a callback  when loading is complete function (b) {    b.dosomething ();  });   // asynchronously loads multiple modules and executes callbacks  when loading is complete function (c, D) {    c.dosomething ();    D.dosomething ();  } );

Note : The require require.async asynchronous callback executes when the synchronization is performed down. require.asynctypically used to load a module that can delay asynchronous loading.

Require.resolve require.resolve(id)

Use the path resolution mechanism inside the module system to parse and return the module path. The function does not load the module and returns only the resolved absolute path.

Define (function(require, exports) {  Console.log (require.resolve ('./b '))  ; // ==> http://example.com/path/to/b.js });

This can be used to obtain the module path, generally used in the plug-in environment or need to dynamically splice the module path of the scene.

Exports Object

exportsis an object that is used to provide a module interface to the outside.

Define (function(require, exports) {  //  externally supplied foo attribute  exports.foo = ' Bar ' ;   // dosomething Methods  for external delivery function () {};});

In addition to exports adding members to an object, you can also use return the direct outward interface.

Define (function(require) {  //  via return directly provides interface  return  {     ' Bar ',    function() {}  };});

If the return statement is a unique code in a module, it can also be simplified to:

define ({  ' bar ',  function() {}});

The above format is particularly suitable for defining JSONP modules.

Special Note : The following wording is wrong!

Define (function(require, exports) {  //  error usage!!!  Exports = {    ' bar ',    function() {}  };});

The correct notation is return to use or assign module.exports values:

Define (function(require, exports, module) {  //  correct notation  Module.exports = {    ' bar ',    function() {}  };});

hint : exports just module.exports a reference. The factory value is exports not changed when it is internally re module.exports -assigned. The exports assignment is therefore invalid and cannot be used to change the module interface.

Module Object

moduleis an object that stores some properties and methods associated with the current module.

Module.id String

Unique identification of the module.

function (Require, exports, module) {  //  Modules code });

definethe first parameter in the above code is the module ID.

Module.uri String

The absolute path of the module is obtained according to the path parsing rules of the module system.

Define (function(require, exports, module) {  console.log (Module.uri);    // ==> http://example.com/path/to/this/file.js });

In general (when there is no define handwriting id parameter in), module.id the value is module.uri exactly the same.

Module.dependencies Array

dependenciesis an array that represents the dependencies of the current module.

Module.exports Object

Interface provided externally by the current module.

passed to   Factory   constructor method   exports   parameter is   module.exports A reference to the   object. The interface is provided only through &NBSP, exports   parameters, and sometimes not all of the developer's needs are met. For example, when the interface of a module is an instance of a class, it needs to be implemented by   module.exports  :

Define (function(require, exports, module) {  //  Exports is a reference to Module.exports  //  true  // re-assigning module.exports to a value  New SomeClass ();   // exports no longer equals module.exports  // false });

Note : The assignment of the pair needs to be module.exports executed synchronously and cannot be placed in the callback function. The following is not possible:

// x.jsdefine (function(require, exports, module) {  //  error usage  SetTimeout (function() {    = {A: "Hello" };   (0);});

In Y.js there is a call to the above x.js:

// y.jsdefine (function(require, exports, module) {  var x = require ('./x ');   //  cannot get the module X's attribute a  / / undefined} immediately;

Summary

This is all the content of the CMD module definition specification. Frequently used APIs only define ,, require , require.async exports , module.exports these five. Other APIs have a good impression, and when needed, check the documentation without having to remember it.

CMD (sea.js) module definition specification

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.