Home > Web Front-end > JS Tutorial > body text

An in-depth chat about modularization in Node.js

青灯夜游
Release: 2022-04-12 20:34:11
forward
2102 people have browsed it

What is modularity? This article will take you through the modularization in Node and introduce the module loading mechanism. I hope it will be helpful to you!

An in-depth chat about modularization in Node.js

1. The basic concept of modularization

1.1 What is modularization

Modularization refers to the process of dividing the system into several modules layer by layer from top to bottom when solving a complex problem. For the entire system, modules are units that can be combined, decomposed and replaced.

Modularization in the programming field is to follow fixed rules and split a large file into multiple small modules that are independent and interdependent.

The benefits of modularizing the code:

  • Improves the reusability of the code

  • Improves the code The maintainability

  • can realize on-demand loading

## 2. Modularization in Node.js

2.1 Classification of modules in Node.js

Node.js According to the different sources of modules, modules are divided into 3 major categories, namely:

  • Built-in modules (built-in modules are officially provided by Node.js, such as fs, path, http, etc.)

  • Custom modules ( Each .js file created by the user is a custom module)

  • Third-party modules (modules developed by third parties are not officially provided built-in modules, nor are they created by users Custom modules need to be downloaded before use)

2.2 Loading the module

Use the powerful require() method to load the required Use built-in modules, user-defined modules, and third-party modules. For example:

An in-depth chat about modularization in Node.js

Note: When using the require() method to load other modules, the code in the loaded module will be executed; The file suffix '.js' can be omitted when loading custom modules.

2.3 Module scope in Node.js

  • What is module scope

Similar to function scope, variables, methods and other members defined in a custom module can only be accessed within the current module. This module-level access restriction is called module scope.

  • Benefits of module scope

Prevents the problem of global variable pollution (if you use script tags to import two js files and two files If the same variable is defined in both, the former one will be overwritten by the latter one)

2.4 Sharing members in the module scope to the outside

1. module object

There is a module object in each .js custom module, which stores information related to the current module. It is printed as follows:

An in-depth chat about modularization in Node.js

2 , module.exports object

In a custom module, you can use the module.exports object to share members within the module for external use.

When the outside world uses the require() method to import a custom module, what is obtained is the object pointed to by module.exports.

3. Points to note when sharing members

When using the require() method to import a module, the import result will always be based on the object pointed to by module.exports.

An in-depth chat about modularization in Node.js

4. exports object

Since the module.exports word is more complicated to write, in order to simplify the code for sharing members externally, Node provides the exports object. By default, exports and module.exports point to the same object. The final shared result is still based on the object pointed to by module.exports.

An in-depth chat about modularization in Node.js

5. Misunderstandings in the use of exports and module.exports

Always remember that when require() a module, what you get will always be what module.exports points to Object:

An in-depth chat about modularization in Node.js

Personal understanding: exports and module.exports originally point to the same object. Just by mounting the data, it still points to the same object. The data mounted by exports can also be obtained by the require module. If one party assigns a value (pointing to another object, then they do not point to the same object, and the require module gets the object pointed to by module.exports, so once one party changes the pointer, the require module will not get the value of exports.)

Note: In order to prevent confusion, it is recommended that you do not use exports and module.exports at the same time in the same module

2.5 Modular specification in Node.jsNode .js follows the CommonJS modular specification, which specifies the characteristics of modules and how modules depend on each other.

CommonJS provisions:

(1) Inside each module, the module variable represents the current module.

(2) The module variable is an object, and its exports attribute (i.e. module.exports) is the external interface.

(3) Loading a module actually loads the module.exports attribute of the module. require() method is used to load modules.

3. npm and packages

3.1 Package

1. What is the third-party module in package

Node.js Also called a bag.

Just like computers and computers refer to the same thing, third-party modules and packages refer to the same concept, but they are called differently.

2. Source of package

Different from built-in modules and custom modules in Node.js, packages are developed by third-party individuals or teams and are free for everyone to use.

Note: The packages in Node.js are all free and open source, and can be downloaded and used for free without paying.

3. Why packages are needed

Since the built-in modules of Node.js only provide some low-level APIs, the efficiency is very low when developing projects based on built-in modules.

The package is encapsulated based on built-in modules, providing a more advanced and convenient API, which greatly improves development efficiency.

The relationship between packages and built-in modules is similar to the relationship between jQuery and the browser's built-in API.

4. Where to download the package

There is an IT company abroad called npm, Inc. This company has a very famous website: www.npmjs.com/ , it is the world's largest package sharing platform. You can search for any package you need from this website, as long as you have enough patience!

To date, more than 11 million developers around the world have developed and shared more than 1.2 million packages for our use through this package sharing platform. npm, Inc. provides a server at the address registry.npmjs.org/ to share all packages externally. We can download the packages we need from this server.

Note:

Search for the package you need from the www.npmjs.com/ website

From registry.npmjs.org / Download the package you need on the server

5. How to download the package

npm, Inc. provides a package management tool. We can use this package management tool fromregistry.npmjs.org/ The server downloads the required packages for local use.

The name of this package management tool is Node Package Manager (referred to as npm package management tool). This package management tool is installed on the user's computer along with the Node.js installation package.

You can execute the npm -v command in the terminal to check the version number of the npm package management tool installed on your computer:

An in-depth chat about modularization in Node.js

3.2 First experience with npm

1. Command to install packages in the project

If you want to install a package with a specified name in the project, you need to run the following command:

npm install 包的完整名称
Copy after login

The above packaging command can be abbreviated into the following format:

npm i 包的完整名称
Copy after login

2. What files are added after the initial packaging?

After the initial packaging is completed, what files are added in the project folder? A folder called node_modules and a configuration file package-lock.json.

in: The node_modules folder is used to store all packages that have been installed in the project. When require() imports a third-party package, it searches for and loads the package from this directory.

package-lock.json configuration file is used to record the download information of each package in the node_modules directory, such as package name, version number, download address, etc.

Note: Programmers should not manually modify any code in the node_modules or package-lock.json files, the npm package management tool will automatically maintain them.

3. Install the specified version of the package

By default, when you use the npm install command to install a package, the latest version of the package will be automatically installed. If you need to install a package of a specified version, you can specify the specific version through the @ symbol after the package name, for example:

npm i moment@2.22.2
Copy after login

4. Semantic version specification of the package

The version number of the package is Defined in the form of "dotted decimal", there are three digits in total, for example, 2.24.0

The meaning of each digit is as follows:

第1位数字:大版本

第2位数字:功能版本

第3位数字:Bug修复版本

版本号提升的规则:只要前面的版本号增长了,则后面的版本号归零。

3.3 包管理配置文件

npm 规定,在项目根目录中,必须提供一个叫做 package.json 的包管理配置文件。用来记录与项目有关的一些配置信息。例如:

  • 项目的名称、版本号、描述等

  • 项目中都用到了哪些包

  • 哪些包只在开发期间会用到

  • 那些包在开发和部署时都需要用到

1、多人协作的问题

遇到的问题:第三方包的体积过大,不方便团队成员之间共享项目源代码。

解决方案:共享时剔除node_modules

2、如何记录项目中安装了哪些包

在项目根目录中,创建一个叫做 package.json 的配置文件,即可用来记录项目中安装了哪些包。从而方便剔除 node_modules 目录之后,在团队成员之间共享项目的源代码。

注意:今后在项目开发中,一定要把 node_modules 文件夹,添加到 .gitignore 忽略文件中。

3、快速创建 package.json

npm 包管理工具提供了一个快捷命令,可以在执行命令时所处的目录中,快速创建 package.json 这个包管理配置文件:

npm init -y
Copy after login

注意:

(1)上述命令只能在英文的目录下成功运行!所以,项目文件夹的名称一定要使用英文命名,不要使用中文,不能出现空格。

(2)@运行 npm install 命令安装包的时候,npm 包管理工具会自动把包的名称和版本号,记录到 package.json 中。

  • 特别注意:现在的版本安装包会自动生成package.json。

4、dependencies 节点

package.json 文件中,有一个 dependencies 节点,专门用来记录您使用 npm install 命令安装了哪些包。

5、一次性安装所有的包

当我们拿到一个剔除了 node_modules 的项目之后,需要先把所有的包下载到项目中,才能将项目运行起来。 否则会报类似于下面的错误:

An in-depth chat about modularization in Node.js

可以运行 npm install 命令(或 npm i)一次性安装所有的依赖包:

An in-depth chat about modularization in Node.js

6、卸载包

可以运行 npm uninstall 命令,来卸载指定的包:

npm uninstall 具体的包名
Copy after login

注意:npm uninstall 命令执行成功后,会把卸载的包,自动从 package.json 的 dependencies 中移除掉。卸载没有简写。

7、devDependencies 节点

如果某些包只在项目开发阶段会用到,在项目上线之后不会用到,则建议把这些包记录到 devDependencies 节点中。

与之对应的,如果某些包在开发和项目上线之后都需要用到,则建议把这些包记录到 dependencies 节点中。

您可以使用如下的命令,将包记录到 devDependencies 节点中:

An in-depth chat about modularization in Node.js

3.4 解决下包速度慢的问题

1、为什么下包速度慢

在使用 npm 下包的时候,默认从国外的 registry.npmjs.org/ 服务器进行下载,因此下包速度会很慢。

2、淘宝 NPM 镜像服务器

淘宝在国内搭建了一个服务器,专门把国外官方服务器上的包同步到国内的服务器,然后在国内提供下包的服务。从而极大的提高了下包的速度。

扩展: 镜像(Mirroring)是一种文件存储形式,一个磁盘上的数据在另一个磁盘上存在一个完全相同的副本即为镜像。

An in-depth chat about modularization in Node.js

3、切换 npm 的下包镜像源

下包的镜像源,指的就是下包的服务器地址。

1An in-depth chat about modularization in Node.js

4、nrm

为了更方便的切换下包的镜像源,我们可以安装 nrm 这个小工具,利用 nrm 提供的终端命令,可以快速查看和切换下包的镜像源。

1An in-depth chat about modularization in Node.js

3.5 包的分类

使用 npm 包管理工具下载的包,共分为两大类,分别是:

  • 项目包

  • 全局包

1、项目包

那些被安装到项目的 node_modules 目录中的包,都是项目包。

项目包又分为两类,分别是:

  • Development dependency package (package recorded in the devDependencies node, only used during development)

  • Core dependency package (recorded in dependencies The packages in the node will be used during development and after the project goes online)

1An in-depth chat about modularization in Node.js

2. Global package When executing the npm install command, if the -g parameter is provided, the package will be installed as a global package.

The global package will be installed in the C:\Users\user directory\AppData\Roaming\npm\node_modules directory.

1An in-depth chat about modularization in Node.js

Note:

(1) Only tool packages need to be installed globally. Because they provide useful terminal commands.

(2) To determine whether a package needs to be installed globally before it can be used, you can refer to the official instructions for use.

3. i5ting_toc

i5ting_toc is a small tool that can convert md documents into html pages. The steps to use are as follows:

1An in-depth chat about modularization in Node.js

3.6 Standard package structure

After clarifying the concept of a package and how to download and use the package, let's take a deeper look at the internal structure of the package.

A standardized package, its composition structure must meet the following three requirements:

(1) The package must exist in a separate directory

(2) Package The top-level directory must contain package.json. This package management configuration file

(3) package.json must contain the three attributes name, version, and main, which respectively represent the name, version number, and package name of the package. entrance.

Note: The above three requirements are the format that a standardized package structure must comply with. For more constraints, please refer to the following URL: https://yarnpkg.com/zh-Hans/docs/package- json

3.7 Develop your own package

1. Basic structure of initialization package

(1) Create a new itheima-tools folder as The root directory of the package

(2) In the itheima-tools folder, create the following three files:

  • package.json (package management configuration file)

  • index.js (entry file of the package)

  • README.md (description document of the package)

2. Initialize package.json

1An in-depth chat about modularization in Node.js

Note: name—is used to inform the name of the application or software package; version—indicates the current version; main —Sets the entry point of the application; description is a short description of the application/software package; keywords—this attribute contains an array of keywords related to the function of the software package (helps to browse the node official website to find the package); license—specifies The license for the software package.

3. Write the package documentation

The README.md file in the root directory of the package is the package usage documentation. Through it, we can write the package usage instructions in markdown format in advance for user convenience.

There are no mandatory requirements for what to write in the README file; as long as the function, usage, precautions, etc. of the package can be clearly described.

3.8 Release package

1. Register npm account

(1) Visit www.npmjs.com/ website, click the sign up button to enter Registration user interface

(2) Fill in account-related information: Full Name, Public Email, Username, Password

(3) Click the Create an Account button to register an account

(4) Log in to your email and click the verification link to verify the account

2. Log in to the npm account

After the npm account registration is completed, you can execute the npm login command in the terminal and enter the user name in sequence. , password (the password is hidden and cannot be seen, just enter it correctly and press Enter), email, and the OTP code sent to the email, you can log in successfully.

Note: Before running the npm login command, you must first switch the server address of the package to the official server of npm. (If you were using the taobao server before, you must switch to the npm official server) Otherwise, the package publishing will fail!

1An in-depth chat about modularization in Node.js

3. Publish the package to npm

After switching the terminal to the root directory of the package, run the npm publish command to publish the package to npm (note: package names cannot be the same, you can go to the official website to check whether there are packages with the same name).

4. Delete the published package

Run the npm unpublish package name --force command to delete the published package from npm.

Note:

(1) The npm unpublish command can only delete packages published within 72 hours

(2) Packages deleted by npm unpublish are not allowed within 24 hours Repeated publishing

(3) Be careful when publishing packages, and try not to publish meaningless packages to npm!

4. Module loading mechanism

4.1 Prioritize loading from cache

The module will be cached after the first load. This also means that calling require() multiple times will not cause the module's code to be executed multiple times.

1An in-depth chat about modularization in Node.js

Note: Whether it is a built-in module, a user-defined module, or a third-party module, they will be loaded from the cache first, thereby improving the loading efficiency of the module.

4.2 Loading mechanism of built-in modules

Built-in modules are modules officially provided by Node.js, and built-in modules have the highest loading priority.

For example: require('fs') always returns the built-in fs module, even if there is a package with the same name in the node_modules directory, it is also called fs.

4.3 Custom module loading mechanism

When using require() to load a custom module, you must specify a path identifier starting with ./ or ../. When loading a custom module, if no path identifier such as ./ or ../ is specified, node will load it as a built-in module or a third-party module.

At the same time, when using require() to import a custom module, if the file extension is omitted, Node.js will try to load the following files in order:

(1) Load according to the exact file name

(2) Complete the .js extension to load

(3) Complete the .json extension to load

(4) Complete the .node extension to load

(5) Loading fails and the terminal reports an error

4.4 Loading mechanism of third-party modules

If passed to The module identifier of require() is not a built-in module, nor does it start with './' or '../', then Node.js will start from the parent directory of the current module and try to load the third party from the /node_modules folder module.

If the corresponding third-party module is not found, move to the parent directory one level above and load it until the root directory of the file system.

For example, assuming require('tools') is called in the 'C:\Users\itheima\project\foo.js' file, Node.js will search in the following order:

(1)C:\Users\itheima\project\node_modules\tools

(2)C:\Users\itheima\node_modules\tools

(3)C:\Users\node_modules \tools

(4)C:\node_modules\tools

4.5 Directory as module

When passing the directory as a module identifier, pass it to require () When loading, there are three loading methods:

(1) Find a file called package.json in the directory being loaded, and look for the main attribute as the entry point for require() loading

(2) If there is no package.json file in the directory, or the main entry does not exist or cannot be parsed, Node.js will try to load the index.js file in the directory.

(3) If the above two steps fail, Node.js will print an error message in the terminal, reporting the missing module: Error: Cannot find module 'xxx'

This article is reproduced from: https://juejin.cn/post/7083445004240158757

For more node-related knowledge, please visit: nodejs tutorial!

The above is the detailed content of An in-depth chat about modularization in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!