Briefly talk about front-end modular development and development specifications

Without foreplay, let's get to the point succinctly - what is modular development?

In modular development, 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 to use.

4 benefits of modular development:

  1 Avoid variable pollution and naming conflicts

  2 Improve the code reuse rate

  3 Improve maintainability

  4 Management of dependencies

 

The front-end modular specification has slowly entered the "Renaissance" era from the primitive barbaric stage. The process of realization is as follows:

a function wrapper

When we talked about function logic, we mentioned that one function of a function is to package a set of statements to implement specific logic. Writing several related functions in one file is the first module.

  function m1(){
    //...
  }

  function m2(){
    //...
  }

The disadvantage of this is obvious, pollutes global variables, and does not guarantee conflicts with other modules, module members seem to be irrelevant

 

two objects

To solve this problem, there is a new way to encapsulate all module members in an object

var module = new Object({

   _count:0,

   m1:function (){  ```  },

   m2:function (){   ```  }                
  
})    

 

In this way, the two functions are wrapped in this object, hey, it looks okay, right? Continue down:

When we want to use it, it is to call the properties of this object

module.m1()

Hey, here comes the problem. This way of writing will expose all members, and the internal state can be changed externally . For example, external code can directly change the value of the counter.

// Bad man's operation 

module._count = 10;

 

In the end, smart humans have found the ultimate new method - execute the function immediately, so that the purpose of not exposing private members can be achieved

 

var module = (function (){

    var _count = 5;
     
    var m1 = function () {`` `};

    var m2 = function (){  ```   };

    return{
         m1:m1,
         m2:m2
    }

})()    

 

The above is the foundation of modular development, and we will talk about other deeper modular development later.

Next, look at the two modular specifications.

 

First understand commonJS.

commonJS is carried forward by nodeJS, which marks the official debut of js modularization.

a defined module

According to the commonJS specification, a single file is a module, and each module is a separate scope, that is, variables defined within the module cannot be read by other modules unless they are properties of the global object.

 

Two module output 

A module has only one export, the module.exports object, and we need to put the content that the module wants to export into this object.

 

Three load modules

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

var name = 'Byron';  
  
function printName(){  
    console.log(name);  
}  
  
function printFullName(firstName){  
    console.log(firstName + name);  
}  
  
module.exports = {  
    printName: printName,  
    printFullName: printFullName  

then load the module

var nameModule = require('./myModel.js');
nameModule.printName ();

 

AMD

Asynchronous Module Definition, the Chinese name is a step module. It is a specification for modular development on the browser side. Since it is not natively supported by js, using the AMD specification for page development requires the use of the corresponding function library, which is the well-known RequireJS. In fact, AMD is RequireJS in the promotion process. Defined normalized outputs.

requireJS mainly solves two problems:

1 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.

2 When js is loaded, the browser will stop the page rendering. The more files are loaded, the longer the page loses response time.

//定义模块

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)

——id  可选参数,用来定义模块的标识,如果没有提供该参数,脚本文件名(去掉拓展名)

——dependencies  是一个当前模块用来的模块名称数组

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

 

在页面上使用require函数加载模块;
require([dependencies], function(){});
require()函数接受两个参数:
——第一个参数是一个数组,表示所依赖的模块;
——第二个参数是一个回调函数,当前面指定的模块都加载成功后,它将被调用。加载的模块会以参数形式传入该函数,从而在回调函数内部就可以使用这些模块

 

AMD推崇的是依赖前置,被提前罗列出来并会背提前下载并执行,后来做了改进,可以不用罗列依赖模块,允许在回调函数中就近使用require引入并下载执行模块。

 

 

CMD

即common module definition

就像AMD有个requireJS,CMD有个浏览器实现的sea.js,sj要解决的问题和rj一样,只不过在模块定义方式和模块加载时机上有所不同。

cmd是sea.js在推广过程中的规范化产出,sea.js是另一种前端模块化工具,它的出现缓解了requireJS的几个痛点。

define(id, deps, factory)
因为CMD推崇一个文件一个模块,所以经常就用文件名作为模块id;
CMD推崇依赖就近,所以一般不在define的参数中写依赖,而是在factory中写。
factory有三个参数:
function(require, exports, module){}
一,require require 是 factory 函数的第一个参数,require 是一个方法,接受 模块标识 作为唯一参数,用来获取其他模块提供的接口;
二,exports exports 是一个对象,用来向外提供模块接口;
三,module module 是一个对象,上面存储了与当前模块相关联的一些属性和方法。 demo
// 定义模块 myModule.js define(function(require, exports, module) { var $ = require('jquery.js') $('div').addClass('active'); }); // 加载模块 seajs.use(['myModule.js'], function(my){ });

 

AMD与CMD区别

总结如下:

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

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

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

 

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


很多人说requireJS是异步加载模块,SeaJS是同步加载模块,这么理解实际上是不准确的,其实加载模块都是异步的,只不过AMD依赖前置,js可以方便知道依赖模块是谁,立即加载,而CMD就近依赖,需要使用把模块变为字符串解析一遍才知道依赖了那些模块,这也是很多人诟病CMD的一点,牺牲性能来带来开发的便利性,实际上解析模块用的时间短到可以忽略。
为什么我们说两个的区别是依赖模块执行时机不同,为什么很多人认为ADM是异步的,CMD是同步的(除了名字的原因。。。)
同样都是异步加载模块,AMD在加载模块完成后就会执行改模块,所有模块都加载执行完后会进入require的回调函数,执行主逻辑,这样的效果就是依赖模块的执行顺序和书写顺序不一定一致,看网络速度,哪个先下载下来,哪个先执行,但是主逻辑一定在所有依赖加载完成后才执行。
CMD加载完某个依赖模块后并不执行,只是下载而已,在所有依赖模块加载完成后进入主逻辑,遇到require语句的时候才执行对应的模块,这样模块的执行顺序和书写顺序是完全一致的。
这也是很多人说AMD用户体验好,因为没有延迟,依赖模块提前执行了,CMD性能好,因为只有用户需要的时候才执行的原因。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325885840&siteId=291194637