4 个核心命令
npm init # 在当前目录建 package.json(交互)
npm init -y # 用默认值(不交互)
npm install # 装 package.json 里所有依赖
npm install express # 装 express 到当前项目
npm install -D vitest # 装到 devDependencies
npm install -g pm2 # 全局装(命令行工具)
npm uninstall express
npm update # 升级到 package.json 允许的最新
npm outdated # 看哪些过期了
npm run dev # 跑 package.json 的 scripts.dev
全局 vs 本地
| 全局 | 本地 | |
|---|---|---|
| 装到 | ~/.npm-global/lib/node_modules |
项目 ./node_modules |
| 用途 | 命令行工具(pm2 / typescript / prettier) | 应用依赖 |
| 推荐 | 少用 | 默认 |
优先用 npx 跑本地工具,不要装全局——避免版本冲突。
npx:跑包但不装全局
npx create-react-app myapp # 不留下全局污染
npx prettier --write . # 用项目本地 prettier
npx some-cli@latest # 永远拉最新版跑
npx 找命令的顺序:
- 当前
./node_modules/.bin/ - 全局
- 都没有 → 从 npm 临时下载
scripts:项目脚本
package.json:
{
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"test": "vitest",
"lint": "eslint ."
}
}
跑:
npm run dev
npm run build
npm test # test 是特殊 alias,不用 run
npm start # start 也是
国内镜像
# 全局设镜像(永久)
npm config set registry https://registry.npmmirror.com
# 单次用
npm install --registry=https://registry.npmmirror.com
# 看当前
npm config get registry
# 切回官方
npm config set registry https://registry.npmjs.org/
npm 现代替代
| 工具 | 特点 |
|---|---|
| pnpm | 硬链接 + 全局缓存 = 省盘 + 快(推荐) |
| yarn | Facebook 出品,曾经更快,现在差距小了 |
| bun | 全栈替代品(含运行时) |
切到 pnpm:
npm install -g pnpm
pnpm install # 替代 npm install
pnpm 命令几乎和 npm 一致——上手 5 分钟。
lockfile
package-lock.json npm
yarn.lock yarn
pnpm-lock.yaml pnpm
bun.lockb bun
必须 commit 进 git——保证团队 / 生产装的是同一个版本树。
清缓存
npm cache clean --force
rm -rf node_modules package-lock.json
npm install # 重装
依赖出诡异问题时这一招通常能修。
坑
- 安装全局包后关掉重开终端才能识别新命令
npm install包名错了可能装个仿冒包——拼写时小心(typosquatting 攻击)- 大型项目
node_modules可能 1G+——加.gitignore
下一篇:package.json 字段精解。