package.json scripts

When using npm (commonly with nodejs), we can pre-define command line commands in the package.json file, using the scripts option.

Use Case: Pre-Standardized Commands Per Organization

Description: Allow teams to standardize commands to allow easy cross-project development and collaboration.

In our example, we will standardize a command extended-test that should be run by all developers before issuing a pull request.

Example package.json for mocha project
{
  "scripts": {
    "extended-test": "echo \"Doing Custom Stuff First\" && mocha"
  },
  "devDependencies": {
    "mocha": "^8.0.1"
  }
}
Example package.json for jest project
{
  "scripts": {
    "extended-test": "echo \"Doing Custom Stuff First\" && jest"
  },
  "devDependencies": {
    "jest": "^26.1.0"
  }
}
Example Invocation (common)
npm run extended-test

Benefit: Developers can abstract away specifics of processes that are common between multiple projects.

Note: In a more mature CI-CD environment, developers would not need to run these commands manually, it would be part of an automated process.

Use Case: Pre-Define Command Line Arguments for Each Environment

{
  "scripts": {
    "report-local": "node tps-report.js --db=\"jdbc:mysql://local-address\" --dry_run=false",
    "report-test": "node tps-report.js --db=\"jdbc:mysql://test-address\" --dry_run=false",
    "report-prod": "node tps-report.js --db=\"jdbc:mysql://prod-address\" --dry_run=true"
  },
  "dependencies": {
    "yargs": "^15.4.1"
  }
}
npm run report-local

This example package.json demonstrates use of the yargs package to pre-define command-line arguments to a script.

This helps prevent user error and allows invocation parameters to be reviewed as part of a pull request, rather than passed as tribal knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *