npm scripts详解
npm scripts
是 Node.js 项目开发中用于定义和执行脚本命令的核心功能,通过 package.json
文件的 scripts
字段配置。以下是深度解析和使用指南:
一、基础语法
- 基本结构
json
{
"scripts": {
"dev": "vite",
"build": "vite build"
}
}
- 键 :脚本名称(如
dev
) - 值 :实际执行的命令(如
vite
)
- 运行脚本
bash
npm run <script-name>
# 例如:
npm run dev
- 特殊脚本名称
脚本名 | 直接执行方式 | 用途 |
---|---|---|
start |
npm start |
应用启动入口 |
test |
npm test |
运行测试 |
prepublish |
自动执行 | 发布前预处理 |
二、进阶特性
- 钩子脚本(生命周期脚本)
json
{
"scripts": {
"prebuild": "rimraf dist", // 在build前自动执行
"build": "vite build",
"postbuild": "echo 'Build completed'" // 在build后自动执行
}
}
常见钩子前缀:pre
(之前)、post
(之后)
- 环境变量传递
bash
npm run dev -- --port 3000
等价于:
bash
vite --port 3000
- 跨平台兼容
使用工具包避免平台差异:
json
{
"scripts": {
"clean": "rimraf dist/*", // 跨平台删除目录
"copy": "cpx \"src/**/*.json\" dist" // 跨平台复制
}
}
推荐工具包:
rimraf
:跨平台rm -rf
cpx
:跨平台文件复制cross-env
:跨平台环境变量设置
- 并行/串行执行
json
{
"scripts": {
"parallel": "npm run task1 & npm run task2", // 并行(Linux)
"series": "npm run task1 && npm run task2", // 串行
"cross": "concurrently \"npm run task1\" \"npm run task2\"" // 跨平台并行
}
}
推荐工具:concurrently
三、典型应用场景
- 开发环境启动
json
{
"scripts": {
"dev": "vite --open",
"dev:debug": "cross-env NODE_OPTIONS='--inspect' vite"
}
}
- 构建流程
json
{
"scripts": {
"build": "run-s clean lint build:*",
"build:js": "rollup -c",
"build:css": "sass src/:dist/",
"clean": "rimraf dist",
"lint": "eslint src"
}
}
使用工具:npm-run-all
(run-s
串行,run-p
并行)
- 测试套件
json
{
"scripts": {
"test": "jest",
"test:watch": "jest --watchAll",
"test:cov": "jest --coverage",
"test:e2e": "cypress run"
}
}
- 项目发布
json
{
"scripts": {
"prepublishOnly": "npm run build && npm test",
"release": "standard-version",
"postpublish": "git push --follow-tags"
}
}
四、高级技巧
- 参数传递
json
{
"scripts": {
"serve": "node server.js",
"start": "npm run serve -- --port 8080"
}
}
- 环境变量控制
json
{
"scripts": {
"build": "cross-env NODE_ENV=production vite build"
}
}
- 快捷命令
json
{
"scripts": {
"d": "npm run dev",
"b": "npm run build"
}
}
- 组合复杂命令
json
{
"scripts": {
"deploy": "npm run build && gh-pages -d dist"
}
}
五、调试与优化
- 查看实际命令
bash
npm run <script> --dry-run
- 性能分析
bash
npm run build --timing
- 错误调试
bash
npm run build --verbose
- 缓存清理
bash
npm cache clean --force
六、最佳实践
-
语义化命名 :如
build:prod
、test:unit
-
文档化脚本:在 README 中说明关键脚本
-
避免长命令:复杂逻辑应拆分为独立脚本或工具脚本
-
跨平台兼容 :始终使用
rimraf
/cross-env
等工具 -
安全防护 :敏感操作添加确认提示:
json{ "scripts": { "reset": "node -e \"if(confirm('确定要重置吗?')) require('fs').rmSync('data', { recursive: true })\"" } }
七、与现代工具集成
- 配合 Vite
json
{
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
}
- 配合 TypeScript
json
{
"scripts": {
"typecheck": "tsc --noEmit"
}
}
- 配合 Monorepo
json
{
"scripts": {
"dev": "turbo run dev",
"build": "turbo run build"
}
}
掌握 npm scripts
能显著提升开发效率,建议根据项目需求组合基础命令,形成自动化工作流。对于复杂场景,可考虑使用更专业的构建工具(如 Gulp 或 Makefile)。