最小版

{
  "name": "myapp",
  "version": "1.0.0",
  "main": "index.js"
}

完整字段速查

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "Short description",
  "author": "WadeLy <hi@wadely.dev>",
  "license": "MIT",
  "homepage": "https://github.com/me/myapp",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/me/myapp.git"
  },

  "type": "module",
  "main": "./dist/index.js",
  "exports": {
    ".": "./dist/index.js",
    "./utils": "./dist/utils.js"
  },
  "bin": {
    "mycli": "./bin/cli.js"
  },

  "scripts": {
    "dev": "tsx watch src/index.ts",
    "build": "tsc",
    "start": "node dist/index.js",
    "test": "vitest"
  },

  "dependencies": {
    "express": "^5.0.0"
  },
  "devDependencies": {
    "typescript": "^5.5.0"
  },
  "peerDependencies": {
    "react": ">=18"
  },

  "engines": {
    "node": ">=22"
  },
  "files": ["dist", "README.md"],
  "private": true
}

关键字段

type: module vs commonjs

"type": "module"        // ESM 模式(用 import)
"type": "commonjs"      // CJS 模式(用 require,默认)

详见下一篇 modules。

main vs exports

"main": "./dist/index.js"      // 老式:入口文件
"exports": {
  ".": "./dist/index.js",       // 现代:精确控制可被 import 的路径
  "./sub": "./dist/sub.js"
}

exports 优先级更高,能禁止访问未声明的路径——库作者推荐用 exports。

bin:让你的包变 CLI 工具

"bin": {
  "mycli": "./bin/cli.js"
}

装这个包后 mycli 就能在命令行用了——npm install -gnpx 都能跑。

./bin/cli.js 文件首行加 shebang:

#!/usr/bin/env node
console.log('CLI is running');

engines:限制 Node 版本

"engines": {
  "node": ">=22"
}

警告(不强制)。CI 加 engine-strict 才会真的拒绝。

private: true

"private": true

防止误发布到 npm 公共仓库——所有非要发布的包都该加

scripts 钩子

特殊 script 名会在某些事件自动跑:

{
  "scripts": {
    "preinstall": "node check-env.js",
    "postinstall": "echo Installed!",
    "prepare": "husky install",
    "prepublishOnly": "npm test"
  }
}

pre*post* 是 hook,自动配对触发。

依赖三类

装哪 用途
dependencies 跑应用要用 业务依赖
devDependencies 开发期才要 测试 / 构建工具
peerDependencies 库作者用 声明"你装我,也要装这个"
npm install express              # → dependencies
npm install -D vitest            # → devDependencies

语义化版本(semver)

^1.2.3   兼容更新(>=1.2.3 <2.0.0)  ← 默认
~1.2.3   补丁更新(>=1.2.3 <1.3.0)
1.2.3    精确锁定
*        任何版本(危险)
>=1.2.3  大于等于

  • private: true 防误发——开源 / 库则要去掉
  • mainexports 同时有,exports 优先
  • dependenciesdevDependencies 别搞错——dev--production 模式下不装
  • scripts不要写绝对路径——用 npxnode_modules/.bin/ 自动解析

下一篇:模块系统(CommonJS vs ESM)。