Home  >  Article  >  Web Front-end  >  What are the methods to implement JS modularity? Explanation of js modularization

What are the methods to implement JS modularity? Explanation of js modularization

不言
不言Original
2018-08-11 15:30:112794browse

What this article brings to you is what are the implementation methods of JS modularization? The explanation of js modularization has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. CommonJS
Generation background: At the beginning, everyone thought that JS was useless and the officially defined API could only build browser-based applications. CommonJS was I can’t stand it any longer, CommonJS API defines many APIs used by common applications (mainly non-browser applications), thereby filling this gap. Its ultimate goal is to provide a standard library similar to Python, Ruby and Java. In this case, developers can use CommonJS API to write applications, which can then run on different JavaScript interpreters and different host environments. In 2009, American programmer Ryan Dahl created the node.js project, which uses the JavaScript language for server-side programming. This marks the official birth of "Javascript modular programming". Because to be honest, in a browser environment, not having modules is not a big problem. After all, the complexity of web programs is limited; but on the server side, there must be modules to interact with the operating system and other applications, otherwise there is no way. programming.

Specific representatives: nodeJs, webpack
Principle: The fundamental reason why browsers are not compatible with CommonJS is the lack of four Node.js environment variables (module, exports, require, global, as long as these four variables can be provided, the browser can load the CommonJS module.
Simple implementation:

var module = {  
exports: {}
};
(function(module, exports) {  
exports.multiply = function (n) { 
return n * 1000 
};
}(module, module.exports))
var f = module.exports.multiply;
f(5) // 5000


The above code provides two external variables, module and exports, to an immediate execution function. The module is placed in this immediate execution function. The output value of the module is placed in module.exports, thus realizing the module Loading.

2. AMD
Generation background: After nodeJS based on the commonJS specification came out, the concept of server-side modules has been formed, but, Due to a major limitation, CommonJS The specification does not apply to browser environments. var math = require('math'); math.add(2, 3);require is synchronous. This is not a problem for the server side, because all modules are stored in the local hard disk and can be loaded synchronously. The waiting time is the reading time of the hard disk. However, for browsers, this is a big problem, because the modules are placed on the server side, and the waiting time depends on the speed of the network. It may take a long time, and the browser is in a "suspended" state. Modules on the browser side cannot use "synchronous loading" (synchronous), but can only use "asynchronous loading" (asynchronous). This is the background for the birth of the AMD specification.

Specific representation: RequireJS
Usage example: require([dependencies], function(){});
require() function accepts two parameters
The first parameter is an array, indicating the modules it depends on
The second parameter is a callback function. When all the previously specified modules are loaded successfully, it will be called. The loaded modules will be passed into the function as parameters, so these modules can be used inside the callback function

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

3, CMD
Generate background: CMD is the Common Module Definition. The CMD specification was developed domestically. Just like AMD has requireJS, CMD has the browser implementation SeaJS. The problems that SeaJS needs to solve are the same as requireJS, but in the module definition. The method and module loading (can be said to be run, parsed) timing are different
Specific representative: Sea.js
Usage example: factory is a function, there are three Parameters, function(require, exports, module)
require is a method that accepts the module ID as the only parameter, used to obtain the interfaces provided by other modules: require(id)
exports is an object, used to export Provide module interface
Module is an object that stores some properties and methods associated with the current module

// 定义模块  myModule.js
define(function(require, exports, module) {  
var $ = require('jquery.js')  
$('p').addClass('active');});
// 加载模块
seajs.use(['myModule.js'], 
function(my){
});

The difference between AMD and CMD:
Execution mechanism : SeaJS's attitude towards modules is lazy execution, while RequireJS's attitude towards modules is pre-execution
Follow the specifications: RequireJS follows the AMD (Asynchronous Module Definition) specification, and Sea.js follows the CMD (Common Module Definition) specification. The difference in specifications leads to different APIs between the two

4, ES6 Modules

Generation background: Before Es6*JavaScript had no module system. It was impossible to split a large program into small files that depended on each other and then assemble them in a simple way. This was very important for development. Large, complex projects pose significant obstacles. In order to solve the problem of module dependency loading, AMD, CMD, and COMMONJS appeared. AMD and CMD (there are also differences between the two, which will be discussed later) are used for the client, and COMMONJS is used for the server. After the emergence of es6, Module is defined Function, and the implementation is quite simple, it can completely replace the existing CommonJS and AMD specifications and become a universal module solution for browsers and servers.
Usage examples: export (throw) import (introduction) export default (when other modules load this module, the import command can specify any name for the anonymous function)

Related recommendations :

JS modularization-RequireJS

javascript modular programming (reprinted), javascript modularization_PHP tutorial

The above is the detailed content of What are the methods to implement JS modularity? Explanation of js modularization. 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