NPM 使用介绍
package.json、依赖类型、版本号语义、lock 文件、常用命令。
Key Points`^` 允许次版本升级,`~` 只允许补丁升级,锁文件保证团队装出同一棵树。
初始化
Bash
npm init -y
npm init # 交互式,逐项填JSON
{
"name": "demo",
"version": "1.0.0",
"type": "commonjs",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js",
"test": "node --test"
},
"dependencies": {},
"devDependencies": {}
}装包
Bash
npm install express # 生产依赖
npm install -D nodemon # 开发依赖
npm install -g typescript # 全局
npm install # 按 lock 文件装
npm ci # 严格按 lock 装,CI 用
npm uninstall express
npm update
npm outdated| Flag | Writes to |
|---|---|
| (无) | dependencies |
-D / --save-dev | devDependencies |
-O / --save-optional | optionalDependencies |
-P / --save-peer | peerDependencies |
版本号语义
Text
1 . 4 . 2
│ │ └── patch 修 bug,不改行为
│ └──────── minor 加功能,向后兼容
└────────────── major 破坏性变更| Range | Matches |
|---|---|
1.4.2 | 只有 1.4.2 |
~1.4.2 | 1.4.x |
^1.4.2 | 1.x.x(不含 2.0.0) |
>=1.4 <2 | 同 ^1.4.0 |
* | 任意版本 |
^0.2.3 only matches 0.2.x — 0.x releases are considered unstable and a minor bump may break compatibility. This is the most common beginner trap.lock 文件
package-lock.json records the exact version and integrity hash of every node in the tree. Commit it, or teammates and CI may resolve different versions. npm ci wipes node_modules and installs strictly from the lock — faster and reproducible.
脚本
JSON
{
"scripts": {
"dev": "node --watch --env-file=.env index.js",
"lint": "eslint .",
"build": "npm run lint && tsc",
"prepublishOnly": "npm run build"
}
}npm run prepends node_modules/.bin to PATH, so scripts can call eslint directly and get the local version without npx. pre/post prefixes run automatically around the main script.
初始化
Bash
npm init -y
npm init # 交互式,逐项填JSON
{
"name": "demo",
"version": "1.0.0",
"type": "commonjs",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js",
"test": "node --test"
},
"dependencies": {},
"devDependencies": {}
}装包
Bash
npm install express # 生产依赖
npm install -D nodemon # 开发依赖
npm install -g typescript # 全局
npm install # 按 lock 文件装
npm ci # 严格按 lock 装,CI 用
npm uninstall express
npm update
npm outdated| 参数 | 写入 |
|---|---|
| (无) | dependencies |
-D / --save-dev | devDependencies |
-O / --save-optional | optionalDependencies |
-P / --save-peer | peerDependencies |
版本号语义
Text
1 . 4 . 2
│ │ └── patch 修 bug,不改行为
│ └──────── minor 加功能,向后兼容
└────────────── major 破坏性变更| 范围 | 匹配 |
|---|---|
1.4.2 | 只有 1.4.2 |
~1.4.2 | 1.4.x |
^1.4.2 | 1.x.x(不含 2.0.0) |
>=1.4 <2 | 同 ^1.4.0 |
* | 任意版本 |
^0.2.3 只匹配 0.2.x —— 0.x 版本被视为不稳定,次版本号也可能破坏兼容。这是新手最容易踩的坑。lock 文件
package-lock.json 记录了整棵依赖树的精确版本 + 完整性哈希。必须提交到 git,否则同事和 CI 装出来的版本可能不同。npm ci 会删掉 node_modules 后严格按 lock 重装,比 npm install 快且可复现。
脚本
JSON
{
"scripts": {
"dev": "node --watch --env-file=.env index.js",
"lint": "eslint .",
"build": "npm run lint && tsc",
"prepublishOnly": "npm run build"
}
}npm run 会把 node_modules/.bin 加进 PATH,所以脚本里直接写 eslint 就能用本地版本,不需要 npx。pre / post 前缀会在主脚本前后自动执行。