Table of Contents
CommonJS
Basic writing method
Specification
AMD
Basic usage
Others
CDM
UMD
ES6 module
export command
import命令
export default命令
Home Web Front-end JS Tutorial Why is modularity needed? Introduction to common modular solutions in js

Why is modularity needed? Introduction to common modular solutions in js

Oct 26, 2018 pm 03:20 PM
es6 javascript Modular

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);
};
Copy after login
<!-- file index.html -->
<script src=&#39;xxx/xxx/a.js&#39;></script>

<script>
    sayName(); // 'aaa'
    
    // code...
    
    var name = 'bbb';
    
    sayName(); // 'bbb'
</script>
Copy after login

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)
};
Copy after login
// file b.js
var getName = function() {
    return 'timo';
};
Copy after login
<script src=&#39;xxx/xxx/b.js&#39;></script>
<script src=&#39;xxx/xxx/a.js&#39;></script>

<script>
    sayName(); // 'timo'
</script>
Copy after login
<script src=&#39;xxx/xxx/a.js&#39;></script>
<script src=&#39;xxx/xxx/b.js&#39;></script>

// Uncaught ReferenceError: getName is not defined
Copy after login

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;
Copy after login
// file b.js
var Obj = require('xxx/xxx/a.js');

Obj.sayHi(); // 'I am timo'
Copy after login

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...
 })
Copy after login

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

Specification

In AMD, the exposed module uses define Function

define(moduleName, [], callback);
Copy after login

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...
})
Copy after login

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;
}));
Copy after login

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;
Copy after login
// file b.js
let a = 1;
let b = 2;
let c = 3;

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

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

import命令

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

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

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

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

export default命令

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

// file a.js

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

Add(1, 2); // 3
Copy after login

上面的代码中,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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles