Node.js package.json常用配置字段(Node.js配置、Node项目配置、Node配置)(package-lock.json、yarn.lock)

文章目录

  • Node.js package.json 配置字段详解
    • 引言
    • 基础元数据字段
      • name
      • version
      • description
      • keywords
      • author
      • license
    • 依赖管理
      • dependencies
      • devDependencies
      • peerDependencies
      • optionalDependencies
      • overrides
    • 脚本配置
      • scripts
    • 发布配置
      • private
      • publishConfig
      • files
      • main
      • module
      • types 或 typings
      • exports
    • 项目环境配置
      • engines
      • os
      • cpu
      • browserslist
    • 工具集成配置
      • eslintConfig
      • babel
      • jest
      • prettier
    • 完整示例
    • 最佳实践
      • 语义化版本控制
      • 依赖锁定
      • 脚本组合
      • 发布前检查
    • 总结

Node.js package.json常用配置字段(Node.js配置、Node项目配置、Node配置)(package-lock.json、yarn.lock)_第1张图片

Node.js package.json 配置字段详解

引言

package.json 是 Node.js 项目的核心配置文件,定义了项目的元数据、依赖关系、脚本命令等关键信息。掌握其配置字段对于构建高效、可维护的项目至关重要。

基础元数据字段

name

"name": "my-awesome-project"

项目命名规则:

  • 必须小于等于214个字符
  • 不能包含大写字母
  • 可以使用连字符和下划线
  • 在发布到npm时,名称必须唯一

version

"version": "1.0.0"

遵循语义化版本规范(SemVer):

  • 主版本号(major):不兼容的API修改
  • 次版本号(minor):向下兼容的功能性新增
  • 修订号(patch):向下兼容的问题修正

description

"description": "一个用于处理文件系统操作的工具库"

简洁描述项目功能,有助于在npm搜索结果中展示。

keywords

"keywords": ["file", "system", "utility", "node"]

关键词数组,帮助他人在npm上发现项目。

author

"author": {
  "name": "张三",
  "email": "[email protected]",
  "url": "https://example.com"
}

也可使用简写形式:

"author": "张三  (https://example.com)"

license

"license": "MIT"

指定项目许可证类型,建议使用SPDX许可证标识符。

依赖管理

dependencies

"dependencies": {
  "express": "^4.18.2",   // ^ 表示兼容最新的次版本和补丁版本
  "lodash": "~4.17.21",   // ~ 表示仅兼容最新的补丁版本
  "axios": "0.27.2"       // 精确版本,固定使用此版本
}

生产环境所需依赖。

devDependencies

"devDependencies": {
  "jest": "^29.0.0",        // 测试框架
  "eslint": "^8.36.0",      // 代码检查工具
  "typescript": "^5.0.2"    // TypeScript编译器
}

仅开发环境所需依赖,生产环境不安装。

peerDependencies

"peerDependencies": {
  "react": "^18.0.0",       // 指定宿主包期望的依赖版本
  "react-dom": "^18.0.0"    // 适用于插件、组件库等场景
}

声明与宿主项目的兼容性依赖。

optionalDependencies

"optionalDependencies": {
  "fsevents": "^2.3.2"      // macOS文件系统事件库,非必须
}

可选依赖,安装失败不会导致npm安装过程中断。

overrides

"overrides": {
  "tough-cookie": "4.1.3",  // 强制使用特定版本,解决安全漏洞
  "foo": {
    "bar": {
      "baz": "1.0.0"        // 嵌套依赖版本控制
    }
  }
}

覆盖依赖树中的特定包版本,解决版本冲突和安全问题。

脚本配置

scripts

"scripts": {
  "start": "node dist/index.js",            // 启动应用
  "dev": "nodemon src/index.js",            // 开发环境启动
  "build": "tsc",                           // 构建应用
  "test": "jest",                           // 运行测试
  "lint": "eslint . --ext .js,.ts",         // 代码检查
  "prepare": "husky install",               // npm安装后自动执行
  "preinstall": "echo '安装前执行的脚本'",  // 安装依赖前执行
  "postinstall": "echo '安装后执行的脚本'"  // 安装依赖后执行
}

定义可通过npm run [脚本名]执行的命令。特殊生命周期脚本如pre*post*会自动在相应命令前后执行。

发布配置

private

"private": true  // 防止意外发布到npm

设置为true时,禁止将包发布到npm仓库。

publishConfig

"publishConfig": {
  "registry": "https://registry.npmjs.org/",   // 指定发布源
  "access": "public",                          // 设置公开访问权限(作用于@scope包)
  "tag": "beta"                                // 发布标签
}

控制包发布行为的配置项。

files

"files": [
  "dist",          // 只包含dist目录
  "lib",           // 只包含lib目录
  "*.md",          // 包含所有.md文件
  "!**/*.test.js"  // 排除所有测试文件
]

指定发布到npm时包含的文件,未指定则默认使用.npmignore.gitignore规则。

main

"main": "dist/index.js"  // CommonJS入口点

指定项目的主入口文件,当导入包时默认加载此文件。

module

"module": "dist/index.esm.js"  // ES模块入口点

ESM格式入口点,支持import/export语法的构建工具会优先使用此字段。

types 或 typings

"types": "dist/index.d.ts"  // TypeScript类型定义文件

指定TypeScript类型定义文件位置。

exports

"exports": {
  ".": {
    "import": "./dist/index.mjs",      // ES模块入口
    "require": "./dist/index.cjs",     // CommonJS入口
    "types": "./dist/index.d.ts"       // 类型定义
  },
  "./utils": {
    "import": "./dist/utils.mjs",      // 子路径导出
    "require": "./dist/utils.cjs"
  }
}

精细控制包导出的模块路径映射,支持条件导出,是现代Node.js包的推荐配置方式。

项目环境配置

engines

"engines": {
  "node": ">=14.0.0",   // 要求Node.js最低版本
  "npm": ">=7.0.0"      // 要求npm最低版本
}

指定项目运行所需的Node.js和npm版本。

os

"os": ["darwin", "linux"]  // 仅支持macOS和Linux系统

限制包可安装的操作系统。

cpu

"cpu": ["x64", "ia32"]  // 仅支持x64和ia32架构

限制包可安装的CPU架构。

browserslist

"browserslist": [
  ">0.2%",               // 市场份额超过0.2%的浏览器
  "not dead",            // 排除已停止更新的浏览器
  "not IE 11",           // 排除IE 11
  "last 2 versions"      // 最新的两个版本
]

指定项目支持的浏览器范围,影响babel、autoprefixer等工具的转译行为。

工具集成配置

eslintConfig

"eslintConfig": {
  "extends": ["eslint:recommended", "plugin:react/recommended"],
  "rules": {
    "no-console": "warn",   // 警告使用console
    "react/prop-types": 0   // 禁用prop-types检查
  }
}

内联ESLint配置,可替代.eslintrc文件。

babel

"babel": {
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": [
    ["@babel/plugin-transform-runtime", { "corejs": 3 }]  // 使用corejs 3版本polyfill
  ]
}

内联Babel配置,可替代.babelrc文件。

jest

"jest": {
  "testEnvironment": "node",           // 测试环境为Node.js
  "collectCoverage": true,             // 收集覆盖率
  "coverageThreshold": {               // 覆盖率阈值
    "global": {
      "branches": 80,
      "functions": 80,
      "lines": 80
    }
  }
}

Jest测试框架配置。

prettier

"prettier": {
  "singleQuote": true,      // 使用单引号
  "printWidth": 100,        // 每行最大长度
  "tabWidth": 2,            // 缩进宽度
  "semi": false             // 不使用分号
}

Prettier代码格式化配置。

完整示例

{
  "name": "modern-node-app",
  "version": "1.2.3",
  "description": "现代Node.js应用示例",
  "keywords": ["node", "example", "modern"],
  "author": "张三 ",
  "license": "MIT",
  "private": true,
  
  "main": "dist/index.js",
  "module": "dist/index.mjs",
  "types": "dist/index.d.ts",
  "exports": {
    ".": {
      "import": "./dist/index.mjs",
      "require": "./dist/index.js",
      "types": "./dist/index.d.ts"
    }
  },
  "files": [
    "dist",
    "README.md"
  ],
  
  "scripts": {
    "start": "node dist/index.js",
    "dev": "nodemon -r dotenv/config src/index.js",
    "build": "tsup src/index.ts --format cjs,esm --dts",
    "test": "jest",
    "lint": "eslint .",
    "prepare": "husky install"
  },
  
  "dependencies": {
    "express": "^4.18.2",
    "dotenv": "^16.0.3",
    "winston": "^3.8.2"
  },
  
  "devDependencies": {
    "@types/express": "^4.17.17",
    "@types/node": "^18.15.11",
    "eslint": "^8.37.0",
    "husky": "^8.0.3",
    "jest": "^29.5.0",
    "nodemon": "^2.0.22",
    "tsup": "^6.7.0",
    "typescript": "^5.0.3"
  },
  
  "engines": {
    "node": ">=16.0.0"
  },
  
  "browserslist": [
    "defaults",
    "not IE 11"
  ]
}

最佳实践

语义化版本控制

严格遵循语义化版本规范,使依赖管理更加可预测:

  • 修复bug:增加补丁版本(1.0.0 → 1.0.1)
  • 新增功能:增加次版本(1.0.0 → 1.1.0)
  • 破坏性变更:增加主版本(1.0.0 → 2.0.0)

依赖锁定

使用package-lock.jsonyarn.lock锁定依赖版本树,确保构建环境一致性。可通过npm配置增强依赖安全性:

"scripts": {
  "install-exact": "npm install --save-exact"  // 安装精确版本
}

脚本组合

巧妙组合npm脚本,提升工作流效率:

"scripts": {
  "prebuild": "rimraf dist",              // 构建前清理目录
  "build": "tsc",                         // 构建
  "postbuild": "node scripts/copy-files.js", // 构建后复制文件
  "validate": "npm-run-all --parallel lint test build" // 并行运行多个脚本
}

发布前检查

使用prepublishOnly脚本确保发布前运行测试和构建:

"scripts": {
  "prepublishOnly": "npm run test && npm run build"
}

总结

package.json 作为Node.js项目的核心配置文件,其丰富的字段设置影响着项目的开发、构建、测试和发布全生命周期。掌握这些配置能力,可以构建更加健壮、可维护的Node.js应用。随着Node.js生态的发展,package.json的配置能力也在不断扩展,跟进最新的最佳实践对提升项目质量至关重要。

你可能感兴趣的:(前端,nodejs,node.js,json)