Detailed explanation of package management tools npm, yarn, cnpm, npx, pnpm (2023)

1. Package management tool npm

(1) Package management tool npm:

  • Node Package Manager, which is the Node package manager;
  • But now it is not just the Node package manager, we are also using it to manage dependent packages in front-end projects;
  • Such as vue, vue-router, vuex, express, koa, react, react-dom, axios, babel, webpack, etc.;

(2) How to download and install npm tools?

  • npm is a management tool of node, so we need to install Node first;
  • Node management tool: https://nodejs.org/en/, the process of installing Node will automatically install the npm tool;

(3) Where can I view and search the packages managed by npm?

  • https://www.npmjs.org/
  • This is the official website where we install related npm packages;

(4) Where are the packages managed by npm stored?

  • We publish our own packages to the registry;
  • When we install a package, it is actually a package downloaded from the registry;

2. npm configuration file

So for a project, how do we use npm to manage so many packages?

  • In fact, each of our projects will have a corresponding configuration file, whether it is a front-end project (Vue, React) or a back-end project (Node);
  • This configuration file will record your project name, version number, project description, etc.;
  • It will also record the information of other libraries that your project depends on and the version number of the dependent library;

This configuration file is package.json

So how to get this configuration file?

  • Method 1: Manually create a project from zero, npm init –y
  • Method 2: Create a project through scaffolding, which will help us generate package.json, and there are related configurations in it

3. Common configuration files

  • npm init # Fill in information when creating
  • npm init -y # use the default for all information


Vue3 project created by Vue CLI4 

 

The react17 project created by create-react-app 

 

4. Common attributes

Required attributes: name, version

  • name is the name of the project;
  • version is the version number of the current project;
  • description is descriptive information, often used as the basic description of the project;
  • author is the relevant information of the author (used when publishing);
  • The license is an open source protocol (used when publishing);

private attribute:

  • The private attribute records whether the current project is private;
  • When the value is true, npm cannot publish it, which is the way to prevent private projects or modules from being published;

main attribute:

Set the entry point of the program.

  • For example, we use the axios module const axios = require('axios');
  • If there is a main attribute, it actually finds the corresponding main attribute to find the file;


scripts attribute

  • The scripts attribute is used to configure some script commands, which exist in the form of key-value pairs;
  • After configuration, we can execute this command through the key of the npm run command;
  • What is the difference between npm start and npm run start?

           1. They are equivalent;
            2. For commonly used start, test, stop, and restart, run can be omitted and run directly through npm start;

dependencies property

  • The dependencies attribute is to specify the packages that need to be depended on regardless of the development environment or the production environment;
  • Usually some library modules vue, vuex, vue-router, react, react-dom, axios, etc. used in the actual development of our project;
  • Corresponding to it is devDependencies;

devDependencies property

  • Some packages are not needed in the production environment, such as webpack, babel, etc.;
  • At this time, we will install it into the devDependencies property through npm install webpack --save-dev;

peerDependencies property

  • Another kind of project dependency is peer-to-peer dependency, that is, a package you depend on, which must be based on another host package;
  • For example, element-plus depends on vue3, and ant design depends on react and react-dom;

5. Dependent version management

We will find that the installed dependency version appears: ^2.0.3 or ~2.0.3, what does this mean?

Npm packages usually need to comply with the semver version specification:

  • semver:https://semver.org/lang/zh-CN/
  • npm semver:https://docs.npmjs.com/misc/semver

The semver version specification is XYZ:

  • X major version number (major): when you make an incompatible API modification (may not be compatible with the previous version);
  • Y minor version number (minor): when you do a backward compatible functional addition (new features are added, but compatible with previous versions);
  • Z revision number (patch): when you do a backward compatible problem fix (no new features, fix bugs in previous versions);

Here we explain the difference between ^ and ~:

  • xyz: Indicates a clear version number;
  • ^xyz: Indicates that x remains unchanged, and y and z always install the latest version;
  • ~xyz: Indicates that x and y remain unchanged, and z always installs the latest version;

6. Common attributes

engines attribute

  • The engines attribute is used to specify the version numbers of Node and NPM;
  • During the installation process, the corresponding engine version will be checked first, and an error will be reported if it does not match;
  • In fact, you can also specify the operating system "os": [ "darwin", "linux" ], but it is rarely used;

browserslist attribute

  • It is used to configure the compatibility of the packaged JavaScript browser, refer to;
  • Otherwise, we need to manually add polyfills to support certain syntax;
  • That is to say, it is an attribute that serves packaging tools such as webpack (here is not a detailed explanation of the working principle of tools such as webpack, so no more details will be given);

7. npm install command

There are two situations for installing npm packages:

  • Global install (global install): npm install webpack -g
  • Project (partial) installation (local install): npm install webpack

Global installation

  • Global installation is to directly install a package globally:
  • For example, install yarn globally: npm install yarn -g

But many people have some misunderstandings about global installation:

  • Usually, the packages installed globally using npm are some toolkits: yarn, webpack, etc.;
  • It is not similar to library files such as axios, express, koa, etc.;
  • So the global installation does not allow us to use libraries such as axios in all projects;

8. Project installation

  • The project installation will generate a node_modules folder in the current directory. When we explained the require search order, we explained under what circumstances the package is searched;
  • Partial installation is divided into development-time dependencies and production-time dependencies:

# Default installation development and production dependencies
npm install axios
npm i axios


# Development depends on
npm install webpack --save-dev npm install webpack -D
npm i webpack –D


# According to the dependent packages in package.json

npm install

9. The principle of npm install

Many students should have known npm install <package> before, but have you thought about its internal principles?

  • What does npm install help us do behind the scenes?
  • We will find that there is another file called package-lock.json, what is its function?
  • Starting from npm5, npm supports caching strategy (pressure from yarn), what is the role of caching?

This is a schematic diagram I drew based on npm install:

npm install will detect if there is a package-lock.json file:

no lock file

  1. Analyze dependencies, because we may depend on other packages, and the same dependencies will occur between multiple packages;
  2. Download the compressed package from the registry warehouse (if we set up a mirror, the compressed package will be downloaded from the mirror server);
  3. After the compressed package is obtained, the compressed package will be cached (starting from npm5);
  4. Unzip the compressed package into the node_modules folder of the project

There is a lock file

  • Detect whether the version of the package in the lock is consistent with that in package.json (it will be detected according to the semver version specification);

Inconsistency, then the dependency relationship will be rebuilt, and the top-level process will be followed directly;

  • In the case of consistency, the cache will be searched first

If not found, it will be downloaded from the registry warehouse and go directly to the top-level process;

  • When found, the compressed file in the cache will be obtained, and the compressed file will be decompressed into the node_modules folder;

10、package-lock.json

Package-lock.json file analysis:

  • name: the name of the project;
  • version: the version of the project;
  • lockfileVersion: the version of the lock file;
  • requires: use requires to track module dependencies;
  • dependencies: project dependencies
  • The current project depends on axios, but axios depends on follow-redirects;
  • The attributes in axios are as follows:

                           1. version indicates the version of axios actually installed;
                           2. resolved is used to record the download address and the location in the registry warehouse;
                           3. requires/dependencies records the dependencies of the current module;
                           4. integrity is used to obtain the index from the cache, and then Obtain the compressed package file through the index;


11. Other npm commands

Here we introduce a few more commonly used ones:

# Uninstall a dependent package:
npm uninstall package
npm uninstall package --save-dev npm uninstall package -D


# Force rebuild
npm rebuild

# clear cache

npm cache clean

There are actually a lot of npm commands:

  • https://docs.npmjs.com/cli-documentation/cli
  • For more commands, you can refer to the official documentation as needed

12. yarn tools

Another node package management tool yarn:

  • yarn is a new JS package management tool jointly launched by Facebook, Google, Exponent and Tilde;
  • Yarn appeared to make up for some defects of early npm;
  • There are many defects in the early npm, such as a series of problems such as slow installation of dependencies, confusion of version dependencies, etc.;
  • Although a lot of upgrades and improvements have been made since the npm5 version, many people still like to use yarn;


13. cnpm tool 

        Due to some special reasons, in some cases we cannot download some required packages from https://registry.npmjs.org well.

# View npm mirror:
npm config get registry


# We can directly set the mirror of npm:
npm config set registry https://registry.npm.taobao.org

But for most people (such as me), I don't want to modify the npm image:

  • First, I don’t want to modify the channel where npm originally downloaded from the official package at will;
  • Second, I am worried that one day Taobao’s mirror image will be hung up or not maintained, and it will have to be changed again;

At this time, we can use cnpm and set cnpm as Taobao's mirror image:

npm install -g cnpm --registry=https://registry.npm.taobao.org

cnpm config get registry # https://r.npm.taobao.org/

        In the future, the installation will directly use cpm instead of npm. For example, the native npm command is: npm install uniq --save, and the cnpm command is: cnpm install uniq --save 

14. npx tool

npx is a command that comes with npm5.2.

npx has many functions, but it is more common to use it to call the instructions of a certain module in the project.

Let's take webpack as an example:

  • The global installation is webpack5.1.3
  • The project is installed with webpack3.6.0

Which command do I use if I execute webpack --version in the terminal?

  • The displayed result will be webpack 5.1.3. In fact, it is used globally. Why?
  • The reason is very simple. When webpack cannot be found in the current directory, it will search globally and execute the command;

How to solve this problem?

   So how to use the project (partial) webpack, there are two common ways:

  • Method 1: Clearly find the webpack under node_module
  • Method 2: Define scripts in scripts to execute webpack;

Method 1: Use the following command in the terminal (in the project root directory)
./node_modules/.bin/webpack --version


Method 2: Modify scripts in package.json

"scripts": {
    "webpack": "webpack --version"
}

Method 3: Use npx

npx webpack --version

The principle of npx is very simple, it will find the corresponding command in the node_modules/.bin directory of the current directory;

15. pnpm tool

15.1. What is pnpm?

What is pnpm? Let's take a look at the official explanation:

pnpm: We can understand it as the abbreviation of performant npm;

Which companies are using it?

The package management tools of many companies or open source projects, including Vue, have switched to pnpm;

15.2. What exactly does pnpm do? 

  • When using npm or Yarn, if you have 100 projects and all of them have the same dependency, then you need to keep 100 copies of the same dependency on disk.
  • If pnpm is used, dependent packages will be stored in a unified location, so:
  • If you use the same version for the same dependency, there is only one file for that dependency on disk;
  • If you need to use different versions of the same dependency package, only the files that differ between versions will be stored;
  • All files are stored in a unified location on the hard drive:

                  When installing a package, all the files it contains will be hard-linked to this location without taking up additional hard disk space;
                  this allows you to easily share the same version of the dependency package between projects;

15.3. pnpm creates a non-flat node_modules directory

       When installing dependencies using npm or Yarn Classic, all packages will be promoted to the root of node_modules.

As a result, the source code can access dependencies that are not set by the current project;

15.4. Installation and use of pnpm 

So how should we install pnpm?

  • The official website provides many ways to install pnpm: https://www.pnpm.cn/installation
  • Because Node has been installed, there is npm in Node, so we can install it through npm;
npm install -g pnpm

Here's a comparison table with npm equivalent commands to help you get started quickly:

npm  command  pnpm  equivalent command
npm install pnpm install
npm install <pkg> pnpm add <pkg>
npm uninstall <pkg> pnpm remove <pkg>
npm run <cmd> pnpm <cmd>

For more commands and usage, please refer to the official website of pnpm: https://pnpm.io/zh/

15.4, pnpm storage store

Before pnpm7.0, the unified storage location was in ~/.pnpm-score;

 

After pnpm7.0, the unified storage location has been changed: <pnpm home directory>/store

  • On Linux, the default is ~/.local/share/pnpm/store
  • On Windows: %LOCALAPPDATA%/pnpm/store
  • On macOS: ~/Library/pnpm/store


We can get this directory with some terminal commands: get the currently active store directory 

pnpm store path

————————————————
Copyright statement: This article is an original article of CSDN blogger "Yaonan", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this article for reprinting statement.

 

Guess you like

Origin blog.csdn.net/YN2000609/article/details/132201196