Node.js 项目中package.json文件中的scripts模块解读

1.定义脚本

在 package.json 文件中,你可以添加一个 scripts 对象。每个键值对代表一个脚本来执行:

1
2
3
4
5
6
7
8
9
{
"scripts": {
"start": "node app.js",
"test": "jest",
"build": "webpack",
"dev": "nodemon app.js",
"lint": "eslint ."
}
}

在这个例子中:

  • "start" 会启动你的应用程序。
  • "test" 运行测试用例。
  • "build" 执行打包操作。
  • "dev" 可能会用 nodemon 来在开发模式下运行你的应用程序,提供热重载功能。
  • "lint" 检查代码风格。

2.执行脚本

2.1使用npm

  • 执行 start 脚本: npm start
  • 执行其他脚本: npm run <script-name>,比如 npm run test 或 npm run build
  • npm start 等同于 npm run start
  • npm test 等同于 npm run test

2.2使用yarn

  • 执行任何脚本: yarn <script-name>。例如:
    • yarn start
    • yarn test
    • yarn build

Yarn 没有像 npm 那样对某些脚本名称有特殊对待,所以所有脚本都用同样的方式执行。

2.3传递参数

如果你想要向脚本传递参数,可以这样做:

  • npm: npm run <script-name> -- --参数名=参数值
  • yarn: yarn <script-name> --参数名=参数值

例如,运行一个需要参数的测试:

1
npm run test -- --watch

或在 yarn 中:

1
yarn test --watch