NPM (Node Package Manager)
NPM 是 Node.js 默认的包管理器,也是世界上最大的软件注册表。
安装与初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| npm --version
npm -v
npm init
npm init -y
npm install
npm i
|
包安装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| npm install express npm install lodash axios moment npm i <package-name>
npm install --save-dev typescript jest eslint npm install -D @types/node @types/express npm i -D vite
npm install -g nodemon typescript create-react-app npm i -g pnpm yarn
npm install express@4.17.1 npm install lodash@^4.17.0 npm install axios@~0.21.0
npm install git+https://github.com/user/repo.git npm install user/repo npm install user/repo#branch
npm install ./local-package npm install /path/to/package
|
包卸载
1 2 3 4 5 6 7
| npm uninstall express npm uninstall -D typescript npm uninstall -g nodemon
npm uninstall lodash axios moment
|
包更新
1 2 3 4 5 6 7 8 9 10 11 12
| npm outdated
npm update
npm update -g typescript
npx npm-check-updates -u npm install
|
npm scripts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| { "scripts": { "start": "node server.js", "dev": "nodemon server.js", "build": "tsc && vite build", "test": "jest", "test:watch": "jest --watch", "test:coverage": "jest --coverage", "lint": "eslint src --ext .ts,.js", "lint:fix": "eslint src --ext .ts,.js --fix", "format": "prettier --write 'src/**/*.{ts,js}'", "clean": "rm -rf dist node_modules/.cache", "prebuild": "npm run clean", "postinstall": "npm run build", "deploy": "npm run build && node deploy.js" } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| npm run dev npm run build npm test
npm run test -- --watch npm run build -- --mode production
npm install npm publish
NODE_ENV=production npm run build
npm install -D cross-env cross-env NODE_ENV=production npm run build
|
package.json 详解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| { "name": "my-project", "version": "1.0.0", "description": "项目描述", "main": "dist/index.js", "module": "dist/index.mjs", "types": "dist/index.d.ts", "type": "module", "exports": { ".": { "import": "./dist/index.mjs", "require": "./dist/index.cjs", "types": "./dist/index.d.ts" }, "./package.json": "./package.json" }, "files": [ "dist", "README.md", "LICENSE" ], "scripts": { "build": "tsc", "test": "jest" }, "keywords": [ "typescript", "library" ], "author": "张三 <zhangsan@example.com>", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/user/repo.git" }, "bugs": { "url": "https://github.com/user/repo/issues" }, "homepage": "https://github.com/user/repo#readme", "dependencies": { "express": "^4.18.0" }, "devDependencies": { "typescript": "^5.0.0" }, "peerDependencies": { "react": ">=16.8.0" }, "optionalDependencies": { "fsevents": "^2.3.0" }, "engines": { "node": ">=18.0.0", "npm": ">=8.0.0" }, "os": [ "darwin", "linux" ], "cpu": [ "x64", "arm64" ], "private": true }
|
字段说明:
name: 包名,发布到 npm 时必须唯一version: 语义化版本号 (major.minor.patch)description: 包描述,帮助他人了解包的用途main: CommonJS 入口文件module: ESM 入口文件(现代打包工具优先使用)types: TypeScript 类型定义文件type: "module" 启用 ESM,"commonjs" 使用 CJSexports: 条件导出,精确控制包的入口files: 发布到 npm 时包含的文件/目录scripts: 可执行的命令脚本keywords: 关键词,帮助他人搜索包dependencies: 生产环境依赖devDependencies: 开发环境依赖peerDependencies: 对等依赖,要求宿主项目提供optionalDependencies: 可选依赖,安装失败不报错engines: 指定 Node.js 和 npm 版本要求os/cpu: 指定操作系统和 CPU 架构限制private: 设为 true 防止意外发布
版本语义 (SemVer)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
"lodash": "4.17.21"
"express": "^4.18.0"
"axios": "~1.4.0"
"lodash": ">=4.0.0 <5.0.0" "lodash": "4.x" "lodash": "4.17.x"
"lodash": "latest" "lodash": "next" "lodash": "*"
"lodash": "5.0.0-beta.1"
|
npm 配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| npm config list npm config list -l
npm config set registry https://registry.npmmirror.com npm config set init-author-name "张三" npm config set save-exact true
npm config get registry
npm config delete registry
registry=https://registry.npmmirror.com save-exact=true
//registry.npmjs.org/:_authToken=your-token-here
npm install --registry=https://registry.npmmirror.com
|
发布包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| npm login npm whoami
npm publish npm publish --tag beta npm publish --access public
npm unpublish <package>@<version>
npm deprecate <package>@<version> "此版本已废弃,请升级到新版本"
npm dist-tag add <package>@<version> <tag> npm dist-tag ls <package> npm dist-tag rm <package> <tag>
|
Yarn
Yarn 是 Facebook 开发的替代包管理器,速度更快且更可靠。
安装
1 2 3 4 5 6 7 8 9
| npm install -g yarn
brew install yarn
corepack enable corepack prepare yarn@stable --activate
|
Yarn Classic (v1) vs Yarn Berry (v2+)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| yarn --version
yarn init yarn init -y
yarn install yarn
yarn add express yarn add -D typescript yarn add -W typescript
yarn add express@^4.18.0 yarn add lodash@~4.17.0
yarn upgrade express yarn upgrade
yarn remove express
yarn global add typescript yarn global bin
yarn dev yarn build yarn test
|
Yarn Berry (v2+) 特性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| yarn set version berry yarn set version stable
yarn install
nodeLinker: node-modules
{ "workspaces": [ "packages/*" ] }
yarn workspace package-name build yarn workspaces foreach run build
|
Yarn vs NPM 命令对照
| 功能 | npm | yarn |
|---|
| 初始化 | npm init | yarn init |
| 安装所有 | npm install | yarn |
| 添加依赖 | npm install <pkg> | yarn add <pkg> |
| 添加开发依赖 | npm i -D <pkg> | yarn add -D <pkg> |
| 移除依赖 | npm uninstall <pkg> | yarn remove <pkg> |
| 全局安装 | npm i -g <pkg> | yarn global add <pkg> |
| 运行脚本 | npm run <script> | yarn <script> |
| 更新依赖 | npm update | yarn upgrade |
| 检查过时 | npm outdated | yarn outdated |
PNPM
PNPM 是"快速、节省磁盘空间的包管理器",使用硬链接和符号链接来节省磁盘空间。
安装
1 2 3 4 5 6 7 8 9 10 11
| npm install -g pnpm
brew install pnpm
curl -fsSL https://get.pnpm.io/install.sh | sh -
Invoke-WebRequest -Uri https://get.pnpm.io/install.ps1 | Invoke-Expression
|
基本使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| pnpm init
pnpm install pnpm i
pnpm add express pnpm add -D typescript pnpm add -g pnpm
pnpm remove express pnpm rm express
pnpm update pnpm up
pnpm dev pnpm build pnpm run dev
pnpm exec tsc pnpm dlx create-react-app my-app
|
PNPM 优势
1. 磁盘空间节省
1 2 3 4 5 6
| pnpm store path du -sh $(pnpm store path)
pnpm store prune
|
2. 严格的依赖管理
1 2 3
| shamefully-hoist=false # 不提升依赖到根目录(默认) strict-peer-dependencies=true # 严格的 peerDependencies 检查
|
3. 工作区支持(Monorepo)
1 2 3 4
| packages: - 'packages
|
1 2 3 4 5 6
| pnpm --filter package-name build pnpm -r build
pnpm --filter package-name add express
|
4. 性能优化
1 2 3 4 5 6 7 8
| pnpm -r --parallel test
pnpm -r build
pnpm -r --filter '...HEAD~1' build
|
PNPM vs NPM vs Yarn
| 特性 | npm | yarn | pnpm |
|---|
| 安装速度 | 中等 | 快 | 最快 |
| 磁盘使用 | 高 | 高 | 低(硬链接) |
| node_modules 结构 | 扁平 | 扁平 | 严格隔离 |
| 幽灵依赖 | 可能 | 可能 | 不可能 |
| Monorepo 支持 | 一般 | 好 | 最好 |
| 离线缓存 | 有 | 有 | 有(store) |
Bun
Bun 是一个快速的全能 JavaScript 运行时,集 runtime、bundler、test runner、包管理器于一体。
安装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| curl -fsSL https://bun.sh/install | bash
powershell -c "irm bun.sh/install.ps1|iex"
brew install oven-sh/bun/bun
npm install -g bun
bun --version bun upgrade
|
包管理器
Bun 的包管理器比 npm 快 25-30 倍。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| bun init bun init -y
bun install bun i
bun add express bun add -d typescript bun add -g typescript
bun remove express bun rm express
bun update
bun run dev bun dev bun run build
bunx tsc bun x create-react-app my-app
|
运行时特性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| bun run index.ts
bun run app.tsx
import { Database } from "bun:sqlite"; const db = new Database("mydb.sqlite"); db.run("CREATE TABLE users (name TEXT, age INTEGER)");
const file = Bun.file("input.txt"); const text = await file.text(); await Bun.write("output.txt", "Hello Bun!");
Bun.serve({ port: 3000, fetch(req) { return new Response("Hello from Bun!"); }, });
bun test
bun build ./index.ts --outdir ./dist bun build ./index.ts --target=browser --outdir ./dist bun build ./index.ts --target=node --outdir ./dist
Bun.serve({ fetch(req, server) { if (server.upgrade(req)) { return; } return new Response("Upgrade required", { status: 426 }); }, websocket: { message(ws, message) { ws.send(`Echo: ${message}`); }, }, });
const apiKey = process.env.API_KEY;
const dbUrl = Bun.env.DATABASE_URL;
process.exit(0);
const result = Bun.spawnSync(["echo", "hello"]); console.log(result.stdout.toString());
const proc = Bun.spawn(["bun", "--version"]); const output = await new Response(proc.stdout).text();
|
性能对比
1 2 3 4 5 6 7 8 9 10 11 12 13
| time node -e "console.log('hello')" time bun -e "console.log('hello')"
time npm install time yarn install time pnpm install time bun install
time node index.js time bun index.js
|
兼容性
Bun 兼容大多数 Node.js API 和 npm 包:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import fs from "fs/promises"; import path from "path"; import { createServer } from "http";
import express from "express"; import React from "react";
import { User } from "./types";
const App = () => <div>Hello</div>;
{ "compilerOptions": { "paths": { "@/*": ["./src/*"] } } }
|
何时使用 Bun
适合使用 Bun 的场景:
- 新项目,追求极致性能
- 需要快速启动的开发服务器
- 简单的脚本和工具
- 全栈应用(需要内置打包器和运行时)
谨慎使用的场景:
- 依赖大量原生 Node.js 模块
- 需要与旧版 Node.js 生态深度集成
- 生产环境需要极高的稳定性保证
迁移建议:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| bun install
bun test
bun dev
bun run build
bun run dist/index.js
bun build ./index.ts --target=node --outdir ./dist node dist/index.js
|
选择建议
小型项目/快速原型
- 推荐: Bun 或 npm
- 理由: 简单快速,开箱即用
中型项目/团队协作
- 推荐: PNPM 或 Yarn
- 理由: 速度快,依赖管理严格,支持工作区
大型项目/Monorepo
- 推荐: PNPM
- 理由: 最佳的工作区支持,节省磁盘空间,严格的依赖隔离
企业级项目/生产环境
- 推荐: npm 或 PNPM
- 理由: 稳定性好,生态成熟,社区支持完善
个人项目/实验性项目
- 推荐: Bun
- 理由: 性能极佳,功能全面,开发体验好
最佳实践
锁定版本
1 2 3 4 5 6 7 8
| { "engines": { "node": ">=18.0.0", "pnpm": ">=8.0.0" }, "packageManager": "pnpm@8.15.0" }
|
使用锁文件
1 2 3 4 5
| git add package-lock.json git add yarn.lock git add pnpm-lock.yaml git add bun.lockb
|
定期更新依赖
1 2 3 4 5 6 7
| npm outdated pnpm outdated
npx npm-check-updates -u npx taze -u
|
审计安全漏洞
1 2 3 4 5 6 7 8 9
| npm audit npm audit fix
pnpm audit
yarn audit
|
清理缓存
1 2 3 4 5 6 7 8 9 10 11
| npm cache clean --force
yarn cache clean
pnpm store prune
bun pm cache rm
|