npm scripts 是在 package.json 的 scripts 字段中定义的命令,通过 npm run <name> 运行。它们标准化项目任务(start、build、test、lint),确保整个团队和 CI 使用相同的命令。Lifecycle hooks 是 npm 在特定时刻自动运行的特殊脚本。
定义和运行脚本
json
npm run dev # any script
npm start # `start` and `test` have shortcuts (no "run" needed)
npm test
脚本可以用 && 链接命令(按顺序运行,失败时停止),并且可以访问本地安装的二进制文件(在 node_modules/.bin 中)而无需路径 — 因此即使 vitest 不是全局安装,"test": "vitest" 也能工作。
{
"scripts": {
"prebuild": "rimraf dist", // runs AUTOMATICALLY before "build"
"build": "tsc",
"postbuild": "echo done" // runs AUTOMATICALLY after "build"
}
}
npm 自动在任何脚本 <name> 之前运行 pre<name>,之后运行 post<name>。因此 npm run build 按顺序运行 prebuild → build → postbuild — 对于设置/清理步骤非常方便。
{
"scripts": {
"postinstall": "node setup.js", // runs after `npm install` completes
"prepare": "husky install" // runs after install (commonly sets up git hooks)
}
}
postinstall 和 prepare 等 hooks 在安装 lifecycle 的特定时刻运行 — 通常用于设置 git hooks(husky)或编译原生依赖。(注意:依赖项中的 postinstall 脚本也是供应链安全的考量。)
npm run test -- --watch # pass args to the script after --
NODE_ENV=production npm start # set an env var for the run
✓ Self-documenting — `package.json` shows all available tasks
✓ Cross-platform-ish, no global installs needed (uses local node_modules/.bin)
✓ Standard across the JS ecosystem — every dev knows `npm run`
npm scripts 是 Node/JS 项目的标准任务运行器 — 它们集中并记录了如何启动、构建、测试和 lint 应用程序,确保每个人(和 CI)都运行相同的命令。
理解脚本组合、自动的 pre/post hooks(用于设置/清理)和 postinstall/prepare 等 lifecycle hooks,让你能够清洁地自动化项目工作流程。
它们是项目工具的