package.json 的作用
它是 Node.js 项目的元数据文件,就像一本“说明书”,描述了:
- 这个项目叫什么;
- 用了哪些依赖;
- 如何运行/构建;
几乎所有 Node.js 生态的工具(npm / pnpm / yarn / bundler / VS Code 插件 / CI / CD 工具)都依赖它。
主要作用分类
package.json 的作用主要有 6 点:
- 项目元信息(name, version, author, license);
- 依赖声明(dependencies, devDependencies, peerDependencies);
- 运行脚本(scripts);
- 入口文件(main, module, types → npm 包必需);
- 工具配置(eslintConfig, browserslist, prettier 等);
- monorepo workspace 支持;
详细说明
项目元信息
描述项目的基本情况。
{
"name": "@essg/nuxt",
"version": "0.0.1",
"description": "My Nuxt project in monorepo",
"author": "James01",
"license": "MIT"
}
- name:项目/包名(可带 scope,比如 @essg/nuxt);
- version:版本号,符合 semver 规范(major.minor.patch);
- description:项目说明;
- license:许可证(MIT, ISC, Apache-2.0 等);
依赖声明
告诉包管理器安装哪些依赖。
{
"dependencies": {
"nuxt": "^3.12.0",
"vue": "^3.4.0"
},
"devDependencies": {
"typescript": "^5.3.0",
"eslint": "^9.0.0"
}
}
- dependencies:生产环境需要的依赖(例如 Nuxt, Vue);
- devDependencies:开发/构建时需要的依赖(TypeScript, ESLint);
- peerDependencies:要求外部环境提供的依赖(常见于库,比如插件要求外部装 Vue);
运行脚本(scripts)
定义快捷命令,运行时 pnpm run <脚本名称>。
{
"scripts": {
"dev": "nuxt dev",
"build": "nuxt build",
"lint": "eslint .",
"test": "vitest"
}
}
入口文件
如果写的是一个可发布的 npm 包:
{
"main": "dist/index.js", // CommonJS 入口
"module": "dist/index.mjs", // ESM 入口
"types": "dist/index.d.ts" // TypeScript 类型
}
这样使用者 import "@essg/utils" 时,能正确找到文件。
工具配置
许多工具(Babel, ESLint, Jest, Prettier 等)支持在 package.json 里写配置:
{
"eslintConfig": {
"extends": "eslint:recommended"
},
"browserslist": [
"last 2 versions",
"not dead"
]
}
monorepo workspace 支持
在 monorepo 场景里,package.json 还用来声明 workspace:
{
"private": true,
"workspaces": [
"apps/*",
"packages/*"
]
}
子项目 apps/nuxt/package.json:
{
"name": "@essg/nuxt",
"version": "0.0.1"
}