第 49 / 105 道49 / 105 · #312
什么是 npm
What is npm
先自己答,再往下看Answer it yourself first
一句话:Node 的包管理器 + 全球最大的包仓库。 它负责装依赖、锁版本、跑脚本。
三件核心事:
- 装依赖—— 读
package.json的dependencies, 递归下载到node_modules。 - 锁版本——
package-lock.json记下每一个包的确切版本和哈希, 保证队友和 CI 装出来的一模一样。它必须提交到版本库。 - 跑脚本——
npm run dev, 而且会把node_modules/.bin加到 PATH,所以能直接写vitest而不用写全路径。
必答的两个区分:
dependenciesvsdevDependencies—— 前者是运行时需要的 (React),后者只在开发和构建时需要 (TypeScript、测试框架、打包工具)。 生产安装可以用npm ci --omit=dev跳过后者。npm installvsnpm 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
dependenciesout ofpackage.jsonand download the whole tree intonode_modules. - Pin versions —
package-lock.jsonrecords the exact version and hash of every package, so a teammate and CI install precisely what you did. It has to be committed. - Run scripts —
npm run dev. It also putsnode_modules/.binon the PATH, which is why you can writevitestinstead of a full path.
Two distinctions you must be able to make:
dependenciesvsdevDependencies— 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 withnpm ci --omit=dev.npm installvsnpm ci—installwill update the lock file when it has to;ciinstalls strictly from the lock and errors out if the two disagree. CI should useci.
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.
这道题的出处:Comes from: 课程里的这一节 →this lesson →用抽认卡过一遍Run a flashcard round