Introduction to node's package management tool

In front-end development, when using node as the runtime environment, npm and yarn are often used as package management tools.

Problems with npm and yarn

NPM

For npm, at its core there is a package.json and package-lock.json file for recording and tracking package versions and dependencies.

The node_modules directory structure of the previous version of npm is

node_modules 
└─ 依赖A 
   ├─ index.js 
   ├─ package.json 
   └─ node_modules 
       └─ 依赖B 
       ├─ index.js 
       └─ package.json
 └─ 依赖C 
   ├─ index.js 
   ├─ package.json 
   └─ node_modules 
       └─ 依赖B 
       ├─ index.js 
       └─ package.json

But it is obvious that due to the repeated installation of dependencies, it is not possible to share dependencies. The current version is like this

node_modules 
└─ 依赖A  
    ├─ index.js 
    ├─ package.json 
    └─ node_modules 
└─ 依赖C   
    ├─ index.js 
    ├─ package.json 
    └─ node_modules 
└─ 依赖B 
    ├─ index.js 
    ├─ package.json 
    └─ node_modules 

node_modulesAll dependencies below will be flattened to the same level. Due to the mechanism of require looking for packages, if both A and C depend on B, then A and C will search upwards when they do not find dependent B in their own node_modules, and finally find dependent package B in their node_modules at the same level. In this way, there will be no repeated downloads. And the dependency level nesting will not be too deep. Because there are no duplicate downloads, all A and C will look for and depend on the same B package. Naturally, it also solves the problem that instances cannot share data

Although this flat structure solves the previous nesting problem, it also brings some other problems:

  • Uncertainty of Dependent Structure
  • Increased complexity of the flattening algorithm
  • Undeclared dependent packages (ghost dependencies) can still be illegally accessed in the project

Yarn's output format hints and download speed are faster than npm.

PNPM

It mainly uses hard links and soft links, which improves the installation speed, saves disk space, and avoids the problems of "doppelgangers" and "phantom dependencies". And what yarn supports: security, offline mode, and faster speed, pnpm supports them all, and the speed is even faster.

Now generally use npm or yarn.

Finally, some packaging tools are introduced.

Commonly used packaging tools include Parcel, Rollup and Webpack, and now Vite is often used, and its functions are not limited to packaging.

Use webpack or Vite for apps, Rollup for libraries

References

  1. pnpm/pnpm: Fast, disk space efficient package manager (github.com)
  2. Node.js (nodejs.org)
  3. Node.js 如何处理 ES6 模块 - 阮一峰的网络日志 (ruanyifeng.com)
  4. Home | Yarn - JavaScript 软件包管理器 | Yarn中文文档 - Yarn中文网 (yarnpkg.cn)
  5. Home | Yarn - JavaScript 软件包管理器 | Yarn中文文档 - Yarn中文网 (yarnpkg.cn)

本文由 mdnice 多平台发布

Guess you like

Origin blog.csdn.net/aqwca/article/details/131147064