Table of Contents
1. CommonJS
4. Summary
Home Web Front-end JS Tutorial Learn the module specifications of node(1) from 0 to 1

Learn the module specifications of node(1) from 0 to 1

Jan 24, 2017 pm 03:30 PM
node module

Before explaining the concepts of CommonJS, AMD, and CMD, we first understand the modularity of js. Modularization, as the name suggests, is to decompose the project according to functions or other logic. Each part only handles one function and decouples the functions to facilitate future development and maintenance. Then modularization must have the following capabilities to split and assemble modules:

  1. Define encapsulated modules;

  2. Define the dependence of the new module on other modules;

  3. can support the introduction of other modules;

Then a set of specifications is needed Guidelines were used to define these capabilities, so CommonJS, AMD, CMD, etc. appeared.

1. CommonJS

CommonJS was originally called ServerJS, which is the specification of js on the server side. This is the specification used by node. According to the CommonJS specification, a single file is a module, require is used to load a module, and exports is used to expose methods or properties in the module to the outside.

For example:

// hello.jsfunction say(username){    console.log( 'hello, '+username );
}

exports.say = say;
Copy after login

=============

// main.jsvar person = require('./hello');

person.say('wenzi'); // hello, wenziperson.say('师少兵'); // hello, 师少兵person.say('NUC'); // hello, NUC
Copy after login

At the same time, # The ##require statement can be written anywhere in the file, as long as it is used before the reference, it does not have to be written at the front of the file. However, in order to make the code easier to read and to intuitively see which modules are currently referenced, it is best to put it at the front of the file.

The difference between exports and module.exports

Some people may have seen using exports directly, and some using module.exports. Here is a brief explanation of the difference between the two.

Let’s take a simple example first:

var a = {name:'wenzi'};var b = a;console.log(a); // {name: "wenzi"}console.log(b); // {name: "wenzi"}
Copy after login
The output results of a and b are the same. Now I change the value of name in b:

b.name = 'shaobing';console.log(a); // {name: "shaobing"}console.log(b); // {name: "shaobing"}
Copy after login
The output results of a and b have changed. I will redeclare b again:

var b = {name:'师少兵'};console.log(a); // {name: "shaobing"}console.log(b); // {name: "师少兵"}
Copy after login
These three examples output three results:

  1. Declare an object and put a Assign a value to b, and then a and b output the same result;

  2. changes the name in b, then the name in a also changes;

  3. The b object is redeclared, then the name in a does not change along with b

Explanation: a is an object, b is a pair of a The references, that is, a and b point to the same memory, so the output in 1 is the same. When b is modified, that is, the contents of a and b pointing to the same memory address have changed, a will also be reflected, so the output of the second example will be the same. When b is overwritten, b points to a new memory, and a still points to the original memory, so the final output will be different.

Then you can derive

exports and module.exports at this time:

  1. module.exports initial value is one Empty object {}

  2. exports is a reference to module.exports

  3. require() returns module.exports instead of exports

If module.exports has a new pointer, the exports will be invalid; if module.exports has not changed, just export it directly.

2. AMD and RequireJS

Speaking of AMD, we have to mention

RequireJS. AMD became independent from the CommonJS community and became the AMD community alone. The popularity of AMD, To a large extent, it also relies on the promotion of RequireJS authors.

In the AMD specification, the default recommended module format is:

// hello.js// 将需要引入的模块全部写入到数组中,然后传递参数进行调用define(['a', 'b'], function(a, ,b){    // do something    return{
        hello : function(username){            console.log( 'hello, '+username );
        }
    }
})
Copy after login
==========

// main.jsdefine(['./hello'], function(h){
    h.hello('wenzi');
})
Copy after login
That is to say, in AMD, modules must be defined using

define, and dependencies are passed in through function parameters. One advantage of this is that all dependencies can be seen at a glance.

3. CMD and seajs

The CMD specification was proposed by the famous Yu Bo in China. The only thing that makes do is

nearby dependence. When it is used, it is That place carries require. SeaJS uses the CMD specification:

// hello.jsdefine(function(require, exports, module){    var a = require('a');    // do a    var b = require( 'b' );    // do b    module.exports.hello = hello; // 对外输出hello})
Copy after login

You can also see the difference between AMD and CMD from here:

AMD usually needs to introduce all dependencies at once and then pass them through parameters; while CMD only introduces them when needed

However, AMD also supports import formats such as CMD, but the internal execution is still based on AMD's logic.

4. Summary

This article introduces the relevant differences and connections between CommonJS, AMD, and CMD specifications. Here is a brief summary:

  1. CommonJS: Each file is a module and does not need to be defined. node uses this specification;

  2. AMD: Use define to define a module and pay attention to Dependency in advance

  3. CMD: Use define to define modules and nearby dependencies

Next, we will start The learning of node is officially started.


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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

WLAN expansion module has stopped [fix] WLAN expansion module has stopped [fix] Feb 19, 2024 pm 02:18 PM

If there is a problem with the WLAN expansion module on your Windows computer, it may cause you to be disconnected from the Internet. This situation is often frustrating, but fortunately, this article provides some simple suggestions that can help you solve this problem and get your wireless connection working properly again. Fix WLAN Extensibility Module Has Stopped If the WLAN Extensibility Module has stopped working on your Windows computer, follow these suggestions to fix it: Run the Network and Internet Troubleshooter to disable and re-enable wireless network connections Restart the WLAN Autoconfiguration Service Modify Power Options Modify Advanced Power Settings Reinstall Network Adapter Driver Run Some Network Commands Now, let’s look at it in detail

WLAN extensibility module cannot start WLAN extensibility module cannot start Feb 19, 2024 pm 05:09 PM

This article details methods to resolve event ID10000, which indicates that the Wireless LAN expansion module cannot start. This error may appear in the event log of Windows 11/10 PC. The WLAN extensibility module is a component of Windows that allows independent hardware vendors (IHVs) and independent software vendors (ISVs) to provide users with customized wireless network features and functionality. It extends the capabilities of native Windows network components by adding Windows default functionality. The WLAN extensibility module is started as part of initialization when the operating system loads network components. If the Wireless LAN Expansion Module encounters a problem and cannot start, you may see an error message in the event viewer log.

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

Python commonly used standard libraries and third-party libraries 2-sys module Python commonly used standard libraries and third-party libraries 2-sys module Apr 10, 2023 pm 02:56 PM

1. Introduction to the sys module The os module introduced earlier is mainly for the operating system, while the sys module in this article is mainly for the Python interpreter. The sys module is a module that comes with Python. It is an interface for interacting with the Python interpreter. The sys module provides many functions and variables to deal with different parts of the Python runtime environment. 2. Commonly used methods of the sys module. You can check which methods are included in the sys module through the dir() method: import sys print(dir(sys))1.sys.argv-Get the command line parameters sys.argv is used to implement the command from outside the program. The program is passed parameters and it is able to obtain the command line parameter column

An in-depth analysis of Node's process management tool 'pm2” An in-depth analysis of Node's process management tool 'pm2” Apr 03, 2023 pm 06:02 PM

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

Python programming: Detailed explanation of the key points of using named tuples Python programming: Detailed explanation of the key points of using named tuples Apr 11, 2023 pm 09:22 PM

Preface This article continues to introduce the Python collection module. This time it mainly introduces the named tuples in it, that is, the use of namedtuple. Without further ado, let’s get started – remember to like, follow and forward~ ^_^Creating named tuples The named tuple class namedTuples in the Python collection gives meaning to each position in the tuple and enhances the readability of the code Sexual and descriptive. They can be used anywhere regular tuples are used, and add the ability to access fields by name rather than positional index. It comes from the Python built-in module collections. The general syntax used is: import collections XxNamedT

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

How to use DateTime in Python How to use DateTime in Python Apr 19, 2023 pm 11:55 PM

All data are automatically assigned a "DOB" (Date of Birth) at the beginning. Therefore, it is inevitable to encounter date and time data when processing data at some point. This tutorial will take you through the datetime module in Python and using some peripheral libraries such as pandas and pytz. In Python, anything related to date and time is handled by the datetime module, which further divides the module into 5 different classes. Classes are simply data types that correspond to objects. The following figure summarizes the 5 datetime classes in Python along with commonly used attributes and examples. 3 useful snippets 1. Convert string to datetime format, maybe using datet

See all articles