Skip to content
On this page

package.json 是 Node.js 项目的配置文件,用于定义项目的元数据、依赖关系、脚本命令以及其他配置信息。它在项目的根目录中,是项目的核心配置文件。

描述配置

  • 描述项目的常见配置字段
json
{
  "name": "01package.json",    // 包名,唯一标识项目
  "version": "1.0.0",          // 版本号,遵循 Major.Minor.Patch 的语义化版本规则
  "author": "",                // 作者信息
  "description": "",           // 项目描述
  "keywords": [],              // 项目的技术关键词,用于搜索
  "license": "ISC",            // 许可证类型
  "homepage": "",              // 项目主页
  "repository": {              // 仓库信息
    "type": "git",           // 仓库类型
    "url": ""                // 仓库地址
  },
  "bugs": {                    // 提交问题的地址
    "url": ""                // 通常是 GitHub 的 issue 页面
  }
}

文件配置

  • 控制项目文件的配置字段
json
{
  "files": ["index.js"],   //项目在进行 npm 发布时,可以通过 files 指定需要跟随一起发布的内容来控制 npm 包的大小,避免安装时间太长。
  "type": "module",       //指定项目的模块类型,可以是 commonjs 或者 module
  "main": "index.js",      //指定项目的入口文件
  "browser": "index.js",   //指定项目在浏览器环境下的入口文件
  "module": "index.js",    //指定项目的模块入口文件
  //当一个项目同时定义了 main,browser 和 module,像 webpack,rollup 等构建工具会感知这些字段,并会根据环境以及不同的模块规范来进行不同的入口文件查找。
  "exports": {
    "require": "./index.js",    //require 方式引入的入口文件
    "import": "./index.js"  //import 方式引入的入口文件
  }
}

脚本配置

  • 项目脚本和依赖的配置字段
json
{
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",  //测试脚本
  },
  "dependencies": {  //生产依赖
    "lodash": "^4.17.21"
  },
  "devDependencies": {  //开发依赖
        "rollup": "^2.56.3",
        "rimraf": "^3.0.2"
  },
  "prepublishOnly": "npm run build",  //在发布前执行的脚本
  "publishConfig": {  //发布配置
    "access": "public",  //发布权限,public 或者 private
    "registry": "https://registry.npmjs.org/"  //发布地址
  },
    "engines": {  //指定项目的运行环境
        "node": ">=10.0.0",
      "npm": ">=6.0.0"
    },
  "browserslist": [  //指定项目的浏览器兼容性 .browserslistrc 单文件配置
    "last 1 version",
    "> 1%",
    "maintained node versions",
    "not dead"
  ],
  "os": ["darwin", "linux"],  //指定项目支持的操作系统
  "cpu": ["x64", "arm"]  //指定项目支持的 CPU 架构
}

第三方配置

  • 集成第三方工具的配置字段
json
{
   "types": "index.d.ts",  //指定项目的类型声明文件
    "typings": "index.d.ts",  //指定项目的类型声明文件
  "unpkg": "dist/index.js",  //指定项目在 unpkg 上的入口文件
   "config": { //配置文件
    "commitizen": {  //commitizen 配置
      "path": "./node_modules/cz-conventional-changelog"  //指定 commitizen 的配置文件
    },
    "commitlint": {  //commitlint 配置
      "extends": ["@commitlint/config-conventional"]  //指定 commitlint 的配置文件
    },
    "husky": {  //husky 配置
      "hooks": {  //指定 husky 的钩子
        "pre-commit": "lint-staged"  //指定 pre-commit 钩子的执行命令
      }
    },
    "lint-staged": {  //lint-staged 配置
      "*.js": ["eslint --fix", "git add"]  //指定 lint-staged 的执行命令
    }
   }
}

要保持清醒 永远不抱有意外的幻想 凭空的期待最要命