DrillLab
第 49 / 105 道49 / 105 · #312

什么是 npm

What is npm

先自己答,再往下看Answer it yourself first

一句话:Node 的包管理器 + 全球最大的包仓库。 它负责装依赖、锁版本、跑脚本。

三件核心事:

  • 装依赖—— 读 package.jsondependencies, 递归下载到 node_modules
  • 锁版本——package-lock.json记下每一个包的确切版本和哈希, 保证队友和 CI 装出来的一模一样。它必须提交到版本库。
  • 跑脚本——npm run dev, 而且会把node_modules/.bin加到 PATH,所以能直接写vitest 而不用写全路径。

必答的两个区分:

  • dependencies vs devDependencies—— 前者是运行时需要的 (React),后者只在开发和构建时需要 (TypeScript、测试框架、打包工具)。 生产安装可以用npm ci --omit=dev 跳过后者。
  • npm install vs npm ci——install 会在需要时更新 lock 文件ci 严格按 lock 装, 对不上就直接报错。CI 里应该用 ci

会追问:^1.2.3~1.2.3 什么区别?」——^ 允许小版本和补丁升级 (<2.0.0),~ 只允许补丁 (<1.3.0)。正是因为 ^ 的存在, lock 文件才必不可少—— 否则不同时间装出来的版本会不同。

In one line: Node’s package manager, plus the largest package registry in the world. It installs dependencies, pins versions and runs scripts.

Three core jobs:

  • Install dependencies — read dependencies out of package.json and download the whole tree into node_modules.
  • Pin versionspackage-lock.json records the exact version and hash of every package, so a teammate and CI install precisely what you did. It has to be committed.
  • Run scriptsnpm run dev. It also puts node_modules/.bin on the PATH, which is why you can write vitest instead of a full path.

Two distinctions you must be able to make:

  • dependencies vs devDependencies — the first is what you need at runtime (React), the second only while developing and building (TypeScript, the test runner, the bundler). A production install can skip the second with npm ci --omit=dev.
  • npm install vs npm ci install will update the lock file when it has to; ci installs strictly from the lock and errors out if the two disagree. CI should use ci.

Follow-up: “What is the difference between ^1.2.3 and ~1.2.3?” — ^ allows minor and patch upgrades (<2.0.0), ~ allows patches only (<1.3.0). It is precisely because ^ exists that the lock file is indispensable — otherwise installing on two different days gives you two different trees.