请详细介绍一些package.json中的配置的作用
package.json 是 Node.js 项目(包括 Vue、React、Angular 等前端项目)中非常核心的配置文件,主要用来定义项目的元信息、依赖、脚本、运行配置等。
1. 基础信息字段
这些字段描述项目本身的元信息,主要用于文档、包发布。
| 字段 | 作用 |
|---|---|
name |
包名(发布到 npm 的名字),必须全小写,不能有空格 |
version |
版本号(遵循 语义化版本规范) |
description |
项目描述(npm search 时会显示) |
author |
作者信息,格式:"name <email>" |
license |
协议,如 MIT、Apache-2.0 |
private |
true 表示私有项目,禁止 npm publish |
示例:
{
"name": "my-app",
"version": "1.0.0",
"description": "A Vue project",
"author": "yh <yh@example.com>",
"license": "MIT",
"private": true
}
2. 依赖相关字段
这些字段控制项目安装哪些包,以及在什么环境安装。
| 字段 | 作用 |
|---|---|
dependencies |
项目运行时依赖(打包后也需要) |
devDependencies |
开发时依赖(编译、构建、测试等) |
peerDependencies |
声明宿主环境必须安装的依赖(自己不安装) |
optionalDependencies |
可选依赖,安装失败不报错 |
bundledDependencies / bundleDependencies |
发布时一并打包的依赖 |
示例:
{
"dependencies": {
"vue": "^2.6.14"
},
"devDependencies": {
"webpack": "^4.44.2"
},
"peerDependencies": {
"vue": ">=2.5.0"
}
}
版本号规则(^、~)
-
^1.2.3:兼容次版本(1.x.x)
-
~1.2.3:兼容补丁版本(1.2.x)
-
1.2.3:固定版本
-
*:任意版本
3. 脚本字段
"scripts" 定义命令,可以用 npm run xxx 或 yarn xxx 执行。
示例:
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "eslint --fix src/**/*.js"
}
常见:
-
start:启动项目(npm start 会默认执行)
-
test:测试命令
-
dev:开发环境
-
build:打包构建
-
lint:代码检查
4. 项目配置字段
这些字段通常由工具或框架使用。
| 字段 | 作用 |
|---|---|
main |
入口文件(Node 项目中 require('xxx') 时加载) |
module |
ES Module 入口(现代打包工具使用) |
browser |
浏览器入口(兼容浏览器环境) |
type |
"module" 表示使用 ESM,否则默认 CommonJS |
bin |
可执行命令的路径(CLI 工具使用) |
files |
发布到 npm 时包含的文件 |
man |
帮助文档路径 |
exports |
控制导出的模块路径(Node 14+ 支持) |
示例:
{
"main": "dist/index.js",
"module": "dist/index.esm.js",
"browser": "dist/index.browser.js",
"type": "module"
}
5. 项目行为控制
| 字段 | 作用 |
|---|---|
engines |
限制 Node 和 npm 版本 |
browserslist |
指定兼容的浏览器范围(Babel、Autoprefixer 使用) |
os |
限制运行系统 |
cpu |
限制 CPU 架构 |
sideEffects |
配置 tree-shaking |
示例:
"engines": {
"node": ">=14.0.0",
"npm": ">=6.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
6. 配置项(工具相关)
很多工具会把配置放到 package.json,而不是单独文件。例如:
-
Babel:"babel":
-
ESLint:"eslintConfig":
-
Prettier:"prettier":
-
PostCSS:"postcss": { "plugins": { "autoprefixer": {} } }
7. 发布相关
| 字段 | 作用 |
|---|---|
repository |
Git 仓库地址 |
bugs |
Bug 反馈地址 |
homepage |
项目主页 |
一个综合示例
{
"name": "my-vue-app",
"version": "1.0.0",
"description": "A Vue project",
"private": true,
"main": "dist/index.js",
"module": "dist/index.esm.js",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "eslint --fix src/**/*.js"
},
"dependencies": {
"vue": "^2.6.14"
},
"devDependencies": {
"webpack": "^4.44.2"
},
"engines": {
"node": ">=14.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
],
"repository": {
"type": "git",
"url": "https://github.com/yh/my-vue-app.git"
}
}
浙公网安备 33010602011771号