search
HomeWeb Front-endJS TutorialUnderstand front-end modularity (CommonJs, AMD and CMD)

There are three front-end module specifications: CommonJs, AMD and CMD.

CommonJs is used on the server side, AMD and CMD are used in the browser environment.

AMD is the standardized output of module definitions during the promotion process of RequireJS.

 CMD is the standardized output of module definition during the promotion process of SeaJS.

AMD: Advance execution (asynchronous loading: dependencies are executed first) + delayed execution

CMD: Delayed execution (run to load, execute in sequence)

Module

FunctionWriting

function f1(){
    //...
}
function f2(){
    //...
}

A module is a file that implements a specific function. Putting several functions in a file constitutes a module . Load this file when needed and call the functions in it.

But doing so will pollute the global variables, there is no guarantee that variable names will not conflict with other modules, and there is no relationship between module members.

 ObjectHow to write

var module = {
  star : 0,
  f1 : function (){
    //...
  },
  f2 : function (){
    //...
  }
};
module.f1();
module.star = 1;

The module is written as an object, and the module members are encapsulated in the object. By calling the objectproperty, you can access the module members. But at the same time, the module members are exposed, and the internal state of the module can be modified by the outside world.

Execute function immediately

var module = (function(){
    var star = 0;
    var f1 = function (){
      console.log('ok');
    };
    var f2 = function (){
      //...
    };
       return {
          f1:f1,
          f2:f2
       };
  })();
module.f1();  //ok
console.log(module.star)  //undefined

Internal private variables cannot be accessed from the outside

CommonJs

CommonJS is a specification for server-side modules, promoted and used by Node. Due to the complexity of server-side programming, it is difficult to interact with the operating system and other applications without modules. The usage is as follows:

math.js
exports.add = function() {
    var sum = 0, i = 0, args = arguments, l = args.length;
    while (i < l) {
      sum += args[i++];
    }
    return sum;
};

increment.js
var add = require(&#39;math&#39;).add;
exports.increment = function(val) {
    return add(val, 1);
};

index.js
var increment = require(&#39;increment&#39;).increment;
var a = increment(1); //2

According to the CommonJS specification:

  • A single file is a module. Each module has a separate scope, that is to say, variables defined within the module cannot be read by other modules unless they are defined as attributes of the global object.

  • #The best way to export module variables is to use the module.exports object.

  • Load the module using the require method, which reads a file and executes it, returning the module.exports object inside the file

Look at the above carefully code, you'll notice that require is synchronous. The module system needs to synchronously read the contents of the module file, compile and execute it to obtain the moduleinterface.

However, there are many problems on the browser side.

On the browser side, the best and easiest way to load JavaScript is to insert the <script> tag in the document. However, script tags are inherently asynchronous, and traditional CommonJS modules cannot be loaded normally in the browser environment. </script>

One of the solutions is to develop a server-side component, perform static analysis on the module code, and return the module and its dependency list to the browser. This works well, but requires additional components to be installed on the server and therefore a number of underlying architecture adjustments.

Another solution is to use a set of standard templates to encapsulate the module definition:

define(function(require, exports, module) {

  // The module code goes here

});

This set of template code provides the opportunity for the module loader to load the module before the module code is executed. , statically analyze the module code and dynamically generate a dependency list.

math.js
define(function(require, exports, module) {
  exports.add = function() {
    var sum = 0, i = 0, args = arguments, l = args.length;
    while (i < l) {
      sum += args[i++];
    }
    return sum;
  };
});

increment.js
define(function(require, exports, module) {
  var add = require(&#39;math&#39;).add;
  exports.increment = function(val) {
    return add(val, 1);
  };
});

index.js
define(function(require, exports, module) {
  var inc = require(&#39;increment&#39;).increment;
  inc(1); // 2
});

AMD

AMD is the abbreviation of "Asynchronous Module Definition", which means "asynchronous module definition". Since it is not natively supported by JavaScript, page development using AMD specifications requires the use of corresponding library functions, which is the famous RequireJS. In fact, AMD is the standardized output of module definitions during the promotion process of RequireJS

It adopts The module is loaded asynchronously, and the loading of the module does not affect the execution of subsequent statements. All statements that depend on this module are defined in a callback function. This callback function will not run until the loading is completed.

RequireJS mainly solves two problems

  • Multiple js files may have dependencies, and the dependent files need to be loaded into the browser earlier than the files that depend on it

  • When js is loaded, the browser will stop page rendering. The more files loaded, the longer the page will lose response time

RequireJs also uses require() The statement loads the module, but unlike CommonJS, it requires two parameters:

The first parameter [module] is an array, and the members inside are the modules to be loaded; the second The parameter callback is the callback function after successful loading. Math.add() and math module loading are not synchronized, and the browser will not freeze.

require([module], callback);

require([increment&#39;], function (increment) {
    increment.add(1);
});

 define() function

  RequireJS定义了一个函数 define,它是全局变量,用来定义模块:

  define(id?, dependencies?, factory);

  参数说明:

  • id:指定义中模块的名字,可选;如果没有提供该参数,模块的名字应该默认为模块加载器请求的指定脚本的名字。如果提供了该参数,模块名必须是“顶级”的和绝对的(不允许相对名字)。

  • 依赖dependencies:是一个当前模块依赖的,已被模块定义的模块标识的数组字面量。
    依赖参数是可选的,如果忽略此参数,它应该默认为["require", "exports", "module"]。然而,如果工厂方法的长度属性小于3,加载器会选择以函数的长度属性指定的参数个数调用工厂方法。

  • 工厂方法factory,模块初始化要执行的函数或对象。如果为函数,它应该只被执行一次。如果是对象,此对象应该为模块的输出值。

  来举个例子看看:

define("alpha", ["require", "exports", "beta"], function (require, exports, beta) {
       exports.verb = function() {
           return beta.verb();
           //Or:
           return require("beta").verb();
       }
   });

  RequireJs使用例子

  require.config是用来定义别名的,在paths属性下配置别名。然后通过requirejs(参数一,参数二);参数一是数组,传入我们需要引用的模块名,第二个参数是个回调函数,回调函数传入一个变量,代替刚才所引入的模块。

main.js
//别名配置
requirejs.config({
    paths: {
        jquery: &#39;jquery.min&#39; //可以省略.js
    }
});
//引入模块,用变量$表示jquery模块
requirejs([&#39;jquery&#39;], function ($) {
    $(&#39;body&#39;).css(&#39;background-color&#39;,&#39;red&#39;);
});

  引入模块也可以只写require()。requirejs通过define()定义模块,定义的参数上同。在此模块内的方法和变量外部是无法访问的,只有通过return返回才行.

math.js
define(&#39;math&#39;,[&#39;jquery&#39;], function ($) {//引入jQuery模块
    return {
        add: function(x,y){
            return x + y;
        }
    };
});

  将该模块命名为math.js保存。

require([&#39;jquery&#39;,&#39;math&#39;], function ($,math) {
    console.log(math.add(10,100));//110
});

  main.js引入模块方法

 CMD

  CMD 即Common Module Definition通用模块定义,CMD规范是国内发展出来的,就像AMD有个requireJS,CMD有个浏览器的实现SeaJS,SeaJS要解决的问题和requireJS一样,只不过在模块定义方式和模块加载(可以说运行、解析)时机上有所不同。

  在 CMD 规范中,一个模块就是一个文件。代码的书写格式如下:

define(function(require, exports, module) {

  // 模块代码

});

  require是可以把其他模块导入进来的一个参数;而exports是可以把模块内的一些属性和方法导出的;module 是一个对象,上面存储了与当前模块相关联的一些属性和方法。

  AMD是依赖关系前置,在定义模块的时候就要声明其依赖的模块;

  CMD是按需加载依赖就近,只有在用到某个模块的时候再去require:

// CMD
define(function(require, exports, module) {
  var a = require(&#39;./a&#39;)
  a.doSomething()
  // 此处略去 100 行
  var b = require(&#39;./b&#39;) // 依赖可以就近书写
  b.doSomething()
  // ... 
})

// AMD 默认推荐的是
define([&#39;./a&#39;, &#39;./b&#39;], function(a, b) { // 依赖必须一开始就写好
  a.doSomething()
  // 此处略去 100 行
  b.doSomething()
  ...
})

  seajs使用例子

// 定义模块  myModule.js
define(function(require, exports, module) {
  var $ = require(&#39;jquery.js&#39;)
  $(&#39;p&#39;).addClass(&#39;active&#39;);
  exports.data = 1;
});

// 加载模块
seajs.use([&#39;myModule.js&#39;], function(my){
    var star= my.data;
    console.log(star);  //1
});

The above is the detailed content of Understand front-end modularity (CommonJs, AMD and CMD). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何使用JS和百度地图实现地图平移功能如何使用JS和百度地图实现地图平移功能Nov 21, 2023 am 10:00 AM

如何使用JS和百度地图实现地图平移功能百度地图是一款广泛使用的地图服务平台,在Web开发中经常用于展示地理信息、定位等功能。本文将介绍如何使用JS和百度地图API实现地图平移功能,并提供具体的代码示例。一、准备工作使用百度地图API前,首先需要在百度地图开放平台(http://lbsyun.baidu.com/)上申请一个开发者账号,并创建一个应用。创建完成

如何使用JS和百度地图实现地图多边形绘制功能如何使用JS和百度地图实现地图多边形绘制功能Nov 21, 2023 am 10:53 AM

如何使用JS和百度地图实现地图多边形绘制功能在现代网页开发中,地图应用已经成为常见的功能之一。而地图上绘制多边形,可以帮助我们将特定区域进行标记,方便用户进行查看和分析。本文将介绍如何使用JS和百度地图API实现地图多边形绘制功能,并提供具体的代码示例。首先,我们需要引入百度地图API。可以利用以下代码在HTML文件中导入百度地图API的JavaScript

js字符串转数组js字符串转数组Aug 03, 2023 pm 01:34 PM

js字符串转数组的方法:1、使用“split()”方法,可以根据指定的分隔符将字符串分割成数组元素;2、使用“Array.from()”方法,可以将可迭代对象或类数组对象转换成真正的数组;3、使用for循环遍历,将每个字符依次添加到数组中;4、使用“Array.split()”方法,通过调用“Array.prototype.forEach()”将一个字符串拆分成数组的快捷方式。

如何使用JS和百度地图实现地图热力图功能如何使用JS和百度地图实现地图热力图功能Nov 21, 2023 am 09:33 AM

如何使用JS和百度地图实现地图热力图功能简介:随着互联网和移动设备的迅速发展,地图成为了一种普遍的应用场景。而热力图作为一种可视化的展示方式,能够帮助我们更直观地了解数据的分布情况。本文将介绍如何使用JS和百度地图API来实现地图热力图的功能,并提供具体的代码示例。准备工作:在开始之前,你需要准备以下事项:一个百度开发者账号,并创建一个应用,获取到相应的AP

js中new操作符做了哪些事情js中new操作符做了哪些事情Nov 13, 2023 pm 04:05 PM

js中new操作符做了:1、创建一个空对象,这个新对象将成为函数的实例;2、将新对象的原型链接到构造函数的原型对象,这样新对象就可以访问构造函数原型对象中定义的属性和方法;3、将构造函数的作用域赋给新对象,这样新对象就可以通过this关键字来引用构造函数中的属性和方法;4、执行构造函数中的代码,构造函数中的代码将用于初始化新对象的属性和方法;5、如果构造函数中没有返回等等。

用JavaScript模拟实现打字小游戏!用JavaScript模拟实现打字小游戏!Aug 07, 2022 am 10:34 AM

这篇文章主要为大家详细介绍了js实现打字小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

php可以读js内部的数组吗php可以读js内部的数组吗Jul 12, 2023 pm 03:41 PM

php在特定情况下可以读js内部的数组。其方法是:1、在JavaScript中,创建一个包含需要传递给PHP的数组的变量;2、使用Ajax技术将该数组发送给PHP脚本。可以使用原生的JavaScript代码或者使用基于Ajax的JavaScript库如jQuery等;3、在PHP脚本中,接收传递过来的数组数据,并进行相应的处理即可。

js是什么编程语言?js是什么编程语言?May 05, 2019 am 10:22 AM

js全称JavaScript,是一种具有函数优先的轻量级,直译式、解释型或即时编译型的高级编程语言,是一种属于网络的高级脚本语言;JavaScript基于原型编程、多范式的动态脚本语言,并且支持面向对象、命令式和声明式,如函数式编程。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment