Home  >  Article  >  Web Front-end  >  What is the difference between front-end modular AMD and CMD?

What is the difference between front-end modular AMD and CMD?

青灯夜游
青灯夜游Original
2020-11-18 09:41:252259browse

Difference: AMD and CMD handle the execution timing of dependent modules differently. AMD advocates pre-dependency, and declares the modules it depends on when defining a module; CMD advocates nearby dependencies, only when a certain Then go to require when you install the module.

What is the difference between front-end modular AMD and CMD?

In the early days of the development of JavaScript, it was to implement simple page interaction logic in just a few words; now CPU and browser performance have been greatly improved. Many page logic has been migrated to the client (form validation, etc.). With the advent of the web2.0 era, Ajax technology has been widely used, jQuery and other front-end libraries have emerged in endlessly, and the front-end code has become increasingly expanded. At this time, JavaScript is used as an embedded The positioning of the scripting language has been shaken, but JavaScript does not provide any obvious help for organizing code. It does not even have the concept of classes, let alone modules. JavaScript’s extremely simple code organization specifications are not enough to manage such a huge scale of code.

ModuleSince JavaScript cannot handle such a large-scale code, we can learn from how other languages ​​handle large-scale programming. There is an important concept in Java -

package

. Logically related codes are organized into the same package. The package is a relatively independent kingdom. There is no need to worry about naming conflicts. What if it is used externally? ? Just importthe corresponding package<pre class="brush:php;toolbar:false">import java.util.ArrayList;</pre>Unfortunately, JavaScript does not provide similar functions because of its positioning during design. Developers need to simulate similar functions to isolate and organize complex JavaScript code is called modularity.

A module is a file that implements a specific function. With a module, we can use other people's code more conveniently, and load whatever module we want for whatever function we want. Module development needs to follow certain norms, and everyone will get messed up if they do their own thing

The process of forming specifications is painful. The pioneers of the front-end started in the stage of slash-and-burn farming and drinking blood, and the development has begun to take shape now. Let’s briefly understand this paragraph Extraordinary journey

Function encapsulation

When we talked about functions, we mentioned that one function of a function is to package a set of statements to implement specific logic, and the scope of JavaScript It is based on functions, so it is natural to use functions as the first step in modularization. Writing several related functions in a file is the first module.

function fn1(){
    statement
}

function fn2(){
    statement
}

This way, when needed, it can be Just call the function in the file where the function is located.

The disadvantages of this approach are obvious: it pollutes global variables, there is no guarantee that variable names will not conflict with other modules, and there is no relationship between module members.

Object

In order to solve the above problem, the object writing method came into being, which can encapsulate all module members in an object

var myModule = {
    var1: 1,

    var2: 2,

    fn1: function(){

    },

    fn2: function(){

    }
}

This way We reference the corresponding file when we want to call the module, and then

myModule.fn2();

This avoids variable pollution, as long as the module name is unique, and members in the same module are also related

It seems A good solution, but it also has flaws. External members can modify internal members at will

myModel.var1 = 100;

This will cause unexpected security problems

Execute the function immediately

You can achieve the purpose of hiding details by executing the function immediately

var myModule = (function(){
    var var1 = 1;
    var var2 = 2;

    function fn1(){

    }

    function fn2(){

    }

    return {
        fn1: fn1,
        fn2: fn2
    };
})();

In this way, variables and functions that we have not exposed cannot be modified outside the module

The above approach is the basis of our modularization. Currently , there are two main types of popular JavaScript module specifications:

CommonJS

and AMD

CommonJS

Let’s talk about CommonJS first Since there is no modular programming on the web page, only the page JavaScript logic is complex, but it can still work, but there must be modules on the server side. Therefore, although JavaScript has been developed on the web side for so many years, the first popular modular specification has Brought by server-side JavaScript applications, the CommonJS specification is carried forward by NodeJS, which marks the official stage of JavaScript modular programming.

    Define module
  1. According to the CommonJS specification, a single file is a module. Each module is 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


  2. Module Output:
  3. The module has only one export,

    module.exports
    object, we need to put the content that the module wants to output into this object

  4. Load module:
  5. Load the module using the

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

    ## Take a look Example
  6. //模块定义 myModel.js
    
    var name = 'Byron';
    
    function printName(){
        console.log(name);
    }
    
    function printFullName(firstName){
        console.log(firstName + name);
    }
    
    module.exports = {
        printName: printName,
        printFullName: printFullName
    }
    
    //加载模块
    
    var nameModule = require('./myModel.js');
    
    nameModule.printName();
Different implementations have different requirements for the path when requiring. Generally, you can omit the

js

extension, use a relative path, or use an absolute path, or even omit the path directly. Use the module name (provided that the module is a built-in system module)

Awkward browser

仔细看上面的代码,会发现require是同步的。模块系统需要同步读取模块文件内容,并编译执行以得到模块接口。

这在服务器端实现很简单,也很自然,然而, 想在浏览器端实现问题却很多。

浏览器端,加载JavaScript最佳、最容易的方式是在document中插入script 标签。但脚本标签天生异步,传统CommonJS模块在浏览器环境中无法正常加载。

解决思路之一是,开发一个服务器端组件,对模块代码作静态分析,将模块与它的依赖列表一起返回给浏览器端。 这很好使,但需要服务器安装额外的组件,并因此要调整一系列底层架构。

另一种解决思路是,用一套标准模板来封装模块定义,但是对于模块应该怎么定义和怎么加载,又产生的分歧:

AMD

AMD 即Asynchronous Module Definition,中文名是异步模块定义的意思。它是一个在浏览器端模块化开发的规范

由于不是JavaScript原生支持,使用AMD规范进行页面开发需要用到对应的库函数,也就是大名鼎鼎RequireJS,实际上AMD 是 RequireJS 在推广过程中对模块定义的规范化的产出

requireJS主要解决两个问题

  1. 多个js文件可能有依赖关系,被依赖的文件需要早于依赖它的文件加载到浏览器
  2. js加载的时候浏览器会停止页面渲染,加载文件越多,页面失去响应时间越长

看一个使用requireJS的例子

// 定义模块 myModule.js
define(['dependency'], function(){
    var name = 'Byron';
    function printName(){
        console.log(name);
    }

    return {
        printName: printName
    };
});

// 加载模块
require(['myModule'], function (my){
  my.printName();
});

语法

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

define(id?, dependencies?, factory);
  1. id:可选参数,用来定义模块的标识,如果没有提供该参数,脚本文件名(去掉拓展名)
  2. dependencies:是一个当前模块依赖的模块名称数组
  3. factory:工厂方法,模块初始化要执行的函数或对象。如果为函数,它应该只被执行一次。如果是对象,此对象应该为模块的输出值

在页面上使用require函数加载模块

require([dependencies], function(){});

require()函数接受两个参数

  1. 第一个参数是一个数组,表示所依赖的模块
  2. 第二个参数是一个回调函数,当前面指定的模块都加载成功后,它将被调用。加载的模块会以参数形式传入该函数,从而在回调函数内部就可以使用这些模块

require()函数在加载依赖的函数的时候是异步加载的,这样浏览器不会失去响应,它指定的回调函数,只有前面的模块都加载成功后,才会运行,解决了依赖性的问题。

CMD

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

语法

Sea.js 推崇一个模块一个文件,遵循统一的写法

define

define(id?, deps?, factory)

因为CMD推崇

  1. 一个文件一个模块,所以经常就用文件名作为模块id
  2. CMD推崇依赖就近,所以一般不在define的参数中写依赖,在factory中写

factory有三个参数

function(require, exports, module)

require

require 是 factory 函数的第一个参数

require(id)

require 是一个方法,接受 模块标识 作为唯一参数,用来获取其他模块提供的接口

exports

exports 是一个对象,用来向外提供模块接口

module

module 是一个对象,上面存储了与当前模块相关联的一些属性和方法

demo

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

// 加载模块
seajs.use(['myModule.js'], function(my){

});

AMD与CMD区别

关于这两个的区别网上可以搜出一堆文章,简单总结一下

最明显的区别就是在模块定义时对依赖的处理不同

  • AMD推崇依赖前置,在定义模块的时候就要声明其依赖的模块

  • CMD推崇就近依赖,只有在用到某个模块的时候再去require

这种区别各有优劣,只是语法上的差距,而且requireJS和SeaJS都支持对方的写法

AMD和CMD最大的区别是对依赖模块的执行时机处理不同,注意不是加载的时机或者方式不同

Many people say that requireJS is an asynchronous loading module, and SeaJS is a synchronous loading module. This understanding is actually inaccurate. In fact, loading modules are all asynchronous, but AMD relies on front-end, and js can easily know who the dependent module is. , loads immediately, and CMD relies on nearby dependencies. You need to use the module to be converted into a string and parse it again to know which modules are dependent on it. This is also a point that many people criticize CMD. It sacrifices performance to bring development convenience. In fact, parsing modules uses The time is short enough to be ignored

Why do we say that the difference between the two is the different execution timing of dependent modules? Why do many people think that ADM is asynchronous and CMD is synchronous (except for the name...)

The modules are also loaded asynchronously. AMD will execute the modified module after loading the module. After all modules are loaded and executed, it will enter the require callback function and execute the main logic. This effect depends on the execution order of the modules. It may not be consistent with the writing order. Depending on the network speed, which one is downloaded first and which one is executed first, but the main logic must be executed after all dependencies are loaded.

CMD will not be executed after loading a certain dependent module. It's just downloading. After all dependent modules are loaded, it enters the main logic. The corresponding module is executed only when the require statement is encountered. In this way, the execution order and writing order of the modules are completely consistent.

This is also what many people say AMD user experience is good because there is no delay and dependent modules are executed in advance. CMD performance is good because it is only executed when the user needs it

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of What is the difference between front-end modular 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