@FahadM to JavaScriptEnglish • 4 days ago

How do you pass command-line arguments into an npm script in package.json?

message-square
0
1
How do you pass command-line arguments into an npm script in package.json?
@FahadM to JavaScriptEnglish • 4 days ago

To pass command-line arguments into an npm run <script> command defined in package.json, place a double dash (--) after the script name followed by your arguments—such as npm run build -- --watch or npm run test -- src/auth.spec.js—so npm forwards all subsequent arguments directly to the underlying script command rather than treating flags like --watch or --silent as npm CLI flags itself.


1. Forwarding Arguments with -- in npm run

When you run npm run <script> -- <args>, npm strips the -- separator and appends <args> to the script defined in package.json:

// package.json example showing scripts that accept forwarded arguments via `--`
{
  "name": "service-worker",
  "private": true,
  "scripts": {
    "lint": "eslint",
    "test": "node --test",
    "deploy": "node scripts/deploy.mjs"
  }
}

// Command-line usage:
// npm run lint -- src/ --max-warnings=0
// npm run test -- tests/unit/
// npm run deploy -- --env=staging --dry-run
  • Always use -- before flags starting with - or --: Without --, npm may interpret --watch or --verbose as npm configuration options instead of passing them to your script.
  • Keep trailing commands simple when forwarding arguments: Appending arguments works cleanly when the script ends with the executable/command ("eslint" -> "eslint src/ --max-warnings=0").

2. Parsing Arguments Safely Inside Node.js Scripts (process.argv / util.parseArgs)

When your package.json script runs a Node.js script, validate and parse arguments explicitly (using node:util’s parseArgs or a Map) rather than relying on fragile positional indices (process.argv[2]) without bounds checks:

// scripts/run-job.mjs — Parse CLI flags safely with explicit validation
import { parseArgs } from "node:util";

function parseJobArguments(argv = process.argv.slice(2)) {
  if (!Array.isArray(argv)) {
    throw new TypeError("Expected argv to be an array of string arguments.");
  }

  try {
    const { values, positionals } = parseArgs({
      args: argv,
      allowPositionals: true,
      strict: true,
      options: {
        env: { type: "string", default: "development" },
        retries: { type: "string", default: "3" },
        dryRun: { type: "boolean", default: false }
      }
    });

    const parsedRetries = Number.parseInt(values.retries, 10);
    if (!Number.isInteger(parsedRetries) || parsedRetries < 0 || parsedRetries > 10) {
      throw new RangeError("Expected --retries to be an integer between 0 and 10.");
    }

    const configMap = new Map([
      ["env", values.env],
      ["retries", parsedRetries],
      ["dryRun", values.dryRun],
      ["targets", positionals]
    ]);

    return configMap;
  } catch (error) {
    throw new Error(`Invalid CLI arguments: ${error.message}`);
  }
}

// Example execution:
// node scripts/run-job.mjs --env=production --retries=5 items-queue
try {
  const options = parseJobArguments();
  console.log("Loaded options:", Object.fromEntries(options.entries()));
} catch (error) {
  console.error(`${error.name}:${error.message}`);
  process.exitCode = 1;
}
  • Use node:util parseArgs in modern Node.js: Avoids hand-rolling flag parsers and gives clear errors on unknown or malformed options.
  • Set process.exitCode = 1 on argument/validation errors: Ensures CI pipelines and parent scripts detect failures cleanly.

3. Middle-of-Script Arguments, Environment Variables, and Cross-Platform Nuances

When arguments need to appear before the end of a command or vary across Windows (cmd.exe / PowerShell) and POSIX shells (bash / zsh), watch out for these practical constraints:

  • Arguments passed after -- are always appended at the end: If a script has a trailing pipe (|) or redirection (> out.txt), appending arguments at the end may not place them where expected—extract into a dedicated .mjs / .js script instead.
  • Quote arguments with spaces or glob patterns consistently: On Unix shells, unquoted * expands before reaching npm; quote patterns like "src/**/*.ts" when the underlying tool should expand globs itself.
  • Prefer explicit flags or cross-env / .env over inline FOO=bar prefixes: Prefixing NODE_ENV=production directly in package.json is not cross-platform on Windows cmd.exe.