search
HomeWeb Front-endJS TutorialWhy is modularity needed? Introduction to common modular solutions in js

This article brings you the content about why modularization is needed? An introduction to commonly used modular solutions in js has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Why modularization is needed

Before the emergence of ES6, the JS language itself did not provide modularization capabilities, which brought some problems to development, the most important of which Two problems should be global pollution and dependency management chaos.

// file a.js
var name = 'aaa';
var sayName = function() {
    console.log(name);
};
<!-- file index.html -->
<script></script>

<script>
    sayName(); // &#39;aaa&#39;
    
    // code...
    
    var name = &#39;bbb&#39;;
    
    sayName(); // &#39;bbb&#39;
</script>

In the above code, we called the sayName function provided by a.js twice and output different results. Obviously, this is because both files have assigned values ​​to the variable name, so they cause each other had an impact. Of course, we can be careful not to define existing variable names when writing code, but when a page references a dozen files with several hundred lines, it is obviously not realistic to remember all the variables that have been defined.

// file a.js
var name = getName();
var sayName = function() {
    console.log(name)
};
// file b.js
var getName = function() {
    return 'timo';
};
<script></script>
<script></script>

<script>
    sayName(); // &#39;timo&#39;
</script>
<script></script>
<script></script>

// Uncaught ReferenceError: getName is not defined

The above code shows that when multiple files have dependencies, we need to ensure the order in which they are introduced, so as to ensure that when running a certain file, its dependencies have been loaded in advance. It is conceivable that in the face of larger files, project, the more dependencies we need to deal with, which is cumbersome and error-prone.

In order to solve these problems, many specifications have emerged in the community that provide modular capabilities for the JS language. With the help of these specifications, our development can be made more convenient and safer.

Common modularization solutions

CommonJS

CommonJS is one of the modularization solutions proposed by the community, and Node.js follows this set plan.

Basic writing method

// file a.js
var obj = {
    sayHi: function() {
        console.log('I am timo');
    };
};

module.exports obj;
// file b.js
var Obj = require('xxx/xxx/a.js');

Obj.sayHi(); // 'I am timo'

In the above code, file a.js is the provider of the module, and file b.js is the caller of the module.

Specification

  1. Each file is a module;

  2. provided within the modulemodule Object, representing the current module;

  3. The module uses exports to expose its own functions/objects/variables, etc.;

  4. The module imports other modules through the require() method; the specifications of

CommonJS are simply the above 4 items. You can understand it by referring to the examples in the basic writing method. , in actual implementation, although Node.js follows the CommonJS specification, it still makes some adjustments to it.

AMD

AMD is one of the modular specifications, and RequireJS follows this set of specifications.

Basic usage

 // file a.js
 define('module', ['m', './xxx/n.js'], function() {
    // code...
 })

In the above code, the file a.js exports the module;

Specification

In AMD, the exposed module uses define Function

define(moduleName, [], callback);

As shown in the above code, the define function has three parameters

  • moduleName. This parameter can be omitted, indicating the name of the module. Generally, it has little effect

  • ['name1', 'name2'], the second parameter is an array, indicating other modules that the current module depends on. If there are no dependent modules, this parameter can be omitted

  • callback, the third parameter is a required parameter, it is a callback function, the inside is the relevant code of the current module

Others

Features of ADM It is dependency front-loading. This is the biggest difference between the ADM specification and the CMD specification to be introduced next. Dependency front-loading means: before running the callback of the currently loaded module, all dependent packages will be loaded first, which is the third step of the define function. The dependent packages specified in the two parameters.

CDM

Basic writing method

 define(function(require, exports, module) {   
    var a = require('./a')  
    a.doSomething();
    // code... 
    var b = require('./b') 
    // code...
})

The above code is the basic writing method of the CMD specification export module;

Specification

It can be seen from the writing method It turns out that the writing method of CMD is very similar to that of AMD. The main difference is the difference in dependency loading timing. As mentioned above, AMD is dependent on front-end, while the CMD specification advocates the proximity principle. Simply put, dependencies are not loaded before the module is run. , during the running of the module, when a certain dependency is needed, load it again.

UMD

When CommonJS, AMD, and CMD are in parallel, a solution is needed that is compatible with them, so that when we develop, we no longer need to consider the specifications followed by dependent modules. , and the emergence of UMD is to solve this problem.

Basic writing method

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        //AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        //Node, CommonJS之类的
        module.exports = factory(require('jquery'));
    } else {
        //浏览器全局变量(root 即 window)
        root.returnExports = factory(root.jQuery);
    }
}(this, function ($) {
    //方法
    function myFunc(){};
    //暴露公共方法
    return myFunc;
}));

The above code is the basic writing method of UMD. As can be seen from the code, it can support both the CommonJS specification and the AMD specification.

ES6 module

The above introduces CommonJS, AMD, CMD and UMD respectively. They are all contributions of the community to the modularization of JS. The fundamental reason for the emergence of this specification is the JS language. It has no modularity capabilities. At present, the latest language specification ES6 of JS has added modularity capabilities to JS. JS’s own modularization solution can completely replace the various specifications currently proposed by the community, and can Commonly used on the browser side and Node side.

The modularization capability in ES6 consists of two commands: export and import. The export command is used to specify the external interface of the module. The import command is used to import functions provided by other modules.

export command

A file in ES6 is a module. The variables/functions inside the module are inaccessible from the outside. If you want to expose the internal functions/variables to other modules, To use it, you need to export it through the export command

// file a.js
export let a = 1;
export let b = 2;
export let c = 3;
// file b.js
let a = 1;
let b = 2;
let c = 3;

export {a, b, c}
// file c.js
export let add = (a, b) => {
    return a + b;
};

上面三个文件的代码,都是通过export命令导出模块内容的示例,其中a.js文件和b.js文件都是导出模块中的变量,作用完全一致但写法不同,一般我们更推荐b.js文件中的写法,原因是这种写法能够在文件最底部清楚地知道当前模块都导出了哪些变量。

import命令

模块通过export命令导出变量/函数等,是为了让其他模块能够导入去使用,在ES6中,文件导入其他模块是通过import命令进行的

// file d.js
import {a, b, c} from './a.js';

上面的代码中,我们引入了a.js文件中的变量a、b、c,import在引入其他模块内的函数/变量时,必须与原模块所暴露出来的函数名/变量名一一对应。
同时,import命令引入的值是只读的,如果尝试对其进行修改,则会报错

import {a} d from './a.js';
a = 2; // Syntax Error : 'a' is read-only;

export default命令

从上面import的介绍可以看到,当需要引入其他模块时,需要知道此模块暴露出的变量名/函数名才可以,这显然有些麻烦,因此ES6还提供了一个import default命令

// file a.js

let add = (a, b) => {
    return a+b
};
export default add;
// file b.js
import Add from './a.js';

Add(1, 2); // 3

上面的代码中,a.js通过export default命令导出了add函数,在b.js文件中引入时,可以随意指定其名称

export default命令是默认导出的意思,既然是默认导出,显然只能有一个,因此每个模块只能执行一次export default命令,其本质是导出了一个名为default的变量或函数。

The above is the detailed content of Why is modularity needed? Introduction to common modular solutions in js. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
es6怎么判断是否为数组es6怎么判断是否为数组Apr 25, 2022 pm 06:43 PM

在es6中,可以利用“Array.isArray()”方法判断对象是否为数组,若判断的对象是数组,返回的结果是true,若判断对象不是数组,返回的结果是false,语法为“Array.isArray(需要检测的js对象)”。

es6中遍历跟迭代的区别是什么es6中遍历跟迭代的区别是什么Apr 26, 2022 pm 02:57 PM

es6中遍历跟迭代的区别是:遍历强调的是要把整个数据依次全部取出来,是访问数据结构的所有元素;而迭代虽然也是依次取出数据,但是并不保证取多少,也不保证把所有的数据取完,是遍历的一种形式。

es6中怎么判断两个对象是否相等es6中怎么判断两个对象是否相等Apr 19, 2022 pm 03:34 PM

在es6中,可用Object对象的is()方法来判断两个对象是否相等,该方法检测两个变量的值是否为同一个值,判断两个对象的引用地址是否一致,语法“Object.is(对象1,对象2)”;该方法会返回布尔值,若返回true则表示两个对象相等。

es6怎么将数字转为字符串es6怎么将数字转为字符串Apr 19, 2022 pm 06:38 PM

转换方法:1、利用“+”给数字拼接一个空字符,语法“数字+""”;2、使用String(),可把对象的值转换为字符串,语法“String(数字对象)”;3、用toString(),可返回数字的字符串表示,语法“数字.toString()”。

sort排序是es6中的吗sort排序是es6中的吗Apr 25, 2022 pm 03:30 PM

sort排序是es6中的;sort排序是es6中用于对数组的元素进行排序的方法,该方法默认不传参,按照字符编码顺序进行排序,排序顺序可以是字母或数字,并按升序或降序,语法为“array.sort(callback(a,b))”。

es6中assign的用法是什么es6中assign的用法是什么May 05, 2022 pm 02:25 PM

在es6中,assign用于对象的合并,可以将源对象的所有可枚举属性复制到目标对象;若目标对象与源对象有同名属性,或多个源对象有同名属性,则后面的属性会覆盖前面的属性,语法为“Object.assign(...)”

es6怎么改变数组数据es6怎么改变数组数据Apr 26, 2022 am 10:08 AM

改变方法:1、利用splice()方法修改,该方法可以直接修改原数组的内容,语法为“数组.splice(开始位置,修改个数,修改后的值)”;2、利用下标访问数组元素,并重新赋值来修改数组数据,语法为“数组[下标值]=修改后的值;”。

import as在es6中的用法是什么import as在es6中的用法是什么Apr 25, 2022 pm 05:19 PM

在es6中,import as用于将若干export导出的内容组合成一个对象返回;ES6的模块化分为导出与导入两个模块,该方法能够将所有的导出内容包裹到指定对象中,语法为“import * as 对象 from ...”。

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools