NPM 使用介绍

package.json、依赖类型、版本号语义、lock 文件、常用命令。

Beginner
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
FlagWrites to
(无)dependencies
-D / --save-devdevDependencies
-O / --save-optionaloptionalDependencies
-P / --save-peerpeerDependencies

版本号语义

Text
1  .  4  .  2
│     │     └── patch  修 bug,不改行为
│     └──────── minor  加功能,向后兼容
└────────────── major  破坏性变更
RangeMatches
1.4.2只有 1.4.2
~1.4.21.4.x
^1.4.21.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.

Friends & Partners