1. The modular

In a JS file can be imported into other JS files, can use the imported JS file variables, data, this feature is called modularity.

Using modular development can be a good solution to variables, function name conflicts, but also flexible solution to the problem of file dependence.

Es5 does not support modularity.

Es6 supports modularization

2. Custom modules (self-defined)

Our code package is module (a separate JS file exists), the general approach is to implement a function, package into a module, and then use this module in other files.

Analogies to JS custom functions, custom modules are used in the following scenarios:

1. Code needs to be reused in the project

2. The code needs to be made available to others

2.1 There are two steps for a custom module:

1. Define a module, that is, create a JS file

2. Use modules to import files where needed

2.2 Defining modules

When you define a module, you create a new JS file. When you name the file, note that

1. It is usually named after a module, like a core module. How about if your module is called myModule, then the JS file should also be called myModele.js

2. Do not duplicate the name of the core module.

3. Export the module

2.3 Exporting Modules

At the end of the file, export the module using modele.exports

Module. exports = Content to exportCopy the code

Note:

  • Module. exports is fixed. Normally, it locates at the bottom of the file only once.

  • Module. exports: represents functions that the current module exposes to other modules

  • It can export objects, arrays, functions, and so on. To organize your code, export objects more often

  • It is not necessary to export all functions, objects, and arrays; the parts that are not exported are just the internal variables of this module

2.4 Importing modules

Once we have finished defining the module, we can use the basic module steps in another file:

Cosnt = require('./ module path ')Copy the code

Once a module has been successfully introduced, it can be used in a similar way to the process of using core modules

// 1. Import modules // Note that relative paths are used here. Const myMath = require('./myMath'); // Please print console.log(myMath) before using it; // 2. Let rs = mymath.add (23,45); console.log(rs)Copy the code

Pay attention to

  • Introduce your own defined modules using require syntax
  • Relative paths must be used here to introduce custom modules

3. There are two ways to export modules

Exports the first :exports the second: Modele. exports

Const myPi = 3.15 const add = (a,b) => a+b; myPi = myPi; exports.add = add; Method 1: exports. MyPi = myPi; exports.add = add; // module.exports. MyPi = myPi; module.exports.add = add; Exports = {myPi, add}Copy the code

Their relationship is:

Exports and modele.exports refer to the same memory region when initialized, and their contents are an empty object. Exports is an alias for module.exports

Copy the code

When defining a module

  • Exports and module.exports are not the same object if you assign a value directly to exports. Exports refers to the new object instead of pointing to module.
  • In imported modules, the module code refers to what module.exports refers to

Export modules only one way (module.exports) is recommended;

4.npm

1.npm

  • npmThe full nameNode Package Manager(Node package manager), which was created to solve the problem of third-party package sharing in Node.
  • npmNo separate installation is required. When Node is installed, it is installed along with itnpm.
  • npm -vCheck the installation.

2. The relationship between package and module

When we went to the NPM website to download the required code, it was presented as a “package” structure on the NPM website. Let’s look at the relationship between packages and modules

5. NPM downloads and uses the package

1. Step 1: Initialize the project

Create an empty folder.

Go to the root directory of the project and start the small black window

Enter the command:

NPM init --yes // To set user information NPM initCopy the code

The init command is used to generate a package.json file in the root directory, which contains basic information about our current project and is the start of everything.

Step 2: Install the package

There is a lot of good code on NPM that we would like to download to use. After generating package.json files, we can install third-party packages. There are millions of packages available on the NPM website (you need to register on the NPM website and log in to see the following data, if you just download the installation package, you don’t need to register) install day.js package

Install day.to js package

### 3 Third package: Use packagesCopy the code

Once we have downloaded a package, we can use it as a core module.

Const constant name = require(” package name); This format is introduced in the same format as the core module

6. Package. The json file

The overall content is a JSON string that describes the current project as a whole. The outermost layer can be thought of as a JS object (each property name is marked with a “”, which is a typical JSON tag). There is a lot of content in this file, we are currently studying the following:

  • Name: Indicates the name of the project. If it is a third-party package, it determines what we should write when require().

  • Version: indicates the version number

  • Keywords: keywords

  • Author: the author

  • Descrption: describe

Others for reference

1. javascript.ruanyifeng.com/nodejs/pack…

2. caibaojian.com/npm/files/p…

7. A node_modules folder

This folder holds the third party packages we downloaded from NPM.

When using the NPM install command, the contents of this folder are modified (the package is downloaded into this folder).

After typing NPM install XXX (assuming the XXX package exists and there are no network errors) :

  1. If there is a package. Json

    (1) Modify package.json file. Depending on the development and production dependencies, decide to include this in devDependencies or in the Dependencies list.

    (2) Modify the node_modules folder

    1. If there is a node_modules folder, create a folder named XXX directly below and remove the package from NPM. If the package has other dependencies, it will be downloaded as well.
    2. If node_modules is not available, create the folder first and then download the corresponding package
  2. If there is no package.json. Will give you a warning.

Description:

  • It is recommended to create package.json using init command before going to Install
  • When sharing code, you generally don’t need to give node_modules to someone else (just like you don’t need to give jquery.js to someone else because they can download it themselves). When they get our code, they run itnpm installInstall the dependency packages yourself.
  • In the module.paths command, you can see that the search path includes the node_modules folder

8. Global installation packages and local installation packages

We use the NPM install command to install the package. In simple terms, we download the package from the NPM official website or the specified image source to our own computer.

  • Global installation: Packages are installed in the system directory (typically node_modules on the system disk).

    • Command: NPM install -g package name or NPM install -g package name

    • Auxiliary tips:

NPM root -g // View the installation directory of the global package. NPM list -g –depth 0 // View the globally installed package

Locally installed (or locally installed), the package is installed in node_modules in the root directory of the current project (the same as package.json) with the command: NPM install package name

8.1 Differences between Global Packages and Local Packages

  • Globally installed packages typically provide commands to execute directly. We did this by installing packages for some utility classes, such as:

Gulp, Nodemon, live-server, NRM, etc.

  • Locally installed packages are project-specific, and we need to use these specific features during development.

A rule of thumb:

  • Commands that use this package to perform tasks require a global installation.

  • To be imported for use through require, a local installation is required.

NPM install NRM -g // step 2: List all source information // (*) indicates the current source NRM ls // Step 3: Switch source as required // for example: Specify NRM use Taotao // Next, install the package you need normallyCopy the code

9. Install the Nodemon package globally

Each time we change the code, we need to restart the HTTP server for the code to take effect:

  1. Enter the small black window
  2. Press CTRL + C to stop the existing HTTP server.
  3. Restart the server manually by running: node index.js.

That’s a bit of a hassle.

Is there a tool that automatically detects our changes and automatically reruns our code? Yes, it’s called Nodemon

9.1 installation nodemon

Install using the NPM package management tool.

Steps:

Open a small black window at any location and enter the following command

Copy the code

Press enter.

This operation requires networking, which takes time depending on the network speed. If no error message is displayed after the command is executed, the installation is successful.

The description of the preceding command is as follows:

  • NPM is a tool for managing third-party modules to be used in Node code. It installs automatically with Node installation: if you install Node, NPM is already installed and you can use it directly.

  • -g indicates global installation. It could also be written after Nodemon. NPM install nodemon-g.

9.2 use nodemon

Once the installation is successful, it is very easy to use: use Nodemon instead of Node in the command. For example, what was: node server.js is now:

nodemon server.js
Copy the code

The nice thing about this is that it automatically listens for changes to the server.js file, and if it changes, it automatically starts running again. Equivalent to:

  node server.js
}
Copy the code

Description:

It is a third party package (tools written by other programmers)

The old Node server.js will still work.

10. NPM package from creation to release

In the work we accumulated some of our own functional code. The code for these functions can be reused in other projects, so we can choose to package the code in [NPM] and download it through NPM Install in the projects that need to be used

10.1 NPM Project Initialization

Create an empty project from the local, take the folder name, go to the official website to see if it is occupied, if it is occupied can not upload

Inspection Method:

If 404 is returned, the project name cannot be found on the NPM website, you can use this command. Otherwise, the description is not availableCopy the code

Initialize the NPM itin –yes command to create a package.json file and set the information for your project file

10.2 Functions

Develop normally, complete your code, and by default,index.js is the entry file for this project

const add = (a,b) => a + b; const sub = (a, b) => a - b; Module. exports = {add, sub}Copy the code

10.3 Switch the current NPM source to the official website

Since we need to upload the package to NPM, make sure the current NPM source is nPMjs.org. There are two related commands.

View the current Registry configuration for NPM.

# to check the current NPM registry configuration, to ensure that is https://registry.npmjs.org # if it isn't, Can use the following command to set the NPM config set registry https://registry.npmjs.org # manually registryCopy the code

10.4 connect the NMP

The NPM adduser command requires three inputs to connect to NPMJS. Username, password, email address (this is the information you use when registering on the NPMJS website). This step can be omitted if this is not your first connection.

You can also use this command to check if it is successful. NPM who am I If it is successful,publish

If you want to exit NPM logout

10.5 Uploading the Package to the NPM

NPM publish error:

  • The package name has been used by someone else.

  • Incorrect package version number: each time a publish, the package version number should be greater than the previous one.

  • The file is too large. You may need to create.npmignore files to set which files to ignore when packaging. Here’s a demo.

10.6 Downloading and Using

You can install it by using the NPM install package name

10.7 remove the packages

NPM unpublish --force // Forcibly delete

10.8 update

  1. Modify the code, save.

  2. Updated the version number. Changes can be made directly in package.json: only larger, not smaller.

  3. To publish

10.9 Summary of PERSONAL experience of NPM

Normally, when we reference someone else’s package and we go and get someone else’s package, we usually just get package.json,

Then download the package through the command

NPM install // Download all the packages required by the package

Because the node_modules file is too large to transfer easily, each package has dependencies, so node-module doesn’t need to be shared with others.






Copy the code