tezvyn:

npm Scripts: Your Project's Command-Line Shortcuts

AI-drafted, machine-checkedSource: docs.npmjs.combeginner
npm Scripts: Your Project's Command-Line Shortcuts

Think of npm scripts as aliases for your project's common command-line tasks, stored in `package.json`. Use them to run build tools, start servers, or execute tests. The main footgun is forgetting `npm run` for custom scripts like `lint` or `build`.

WHY IT EXISTS: Projects often require running complex, multi-step commands for tasks like testing, building, and deploying. Remembering these commands, ensuring all team members use the same flags, and managing them becomes difficult. npm scripts solve this by providing a central, version-controlled place to define and run these tasks.

THE MENTAL MODEL: npm scripts are like a project-specific command-line alias system. You define a named script in your package.json file, which maps a short name (like dev) to a longer shell command (like nodemon --watch src src/index.js). Anyone with the project can then run npm run dev without needing to know the underlying command.

HOW IT WORKS: The scripts field in package.json is a JSON object where keys are the script names and values are the commands to execute. When you run npm run <script-name>, npm temporarily adds your project's node_modules/.bin directory to the system's PATH. This lets you execute command-line tools from your project's dependencies (like jest or webpack) directly by name, without needing global installation.

WHEN TO USE IT: Use scripts to automate any repetitive task in your development workflow. This is ideal for starting servers, running linters and formatters, executing test suites, compiling code (like TypeScript or Sass), and creating production builds. It's the standard way to manage a JavaScript project's lifecycle.

WHEN NOT TO USE IT: Avoid putting long, complex shell logic directly inside package.json. For multi-step processes with conditional logic, it's better to write a separate shell script (.sh) or Node.js script (.js) and have the npm script simply execute that file. This keeps your package.json clean and your logic more maintainable.

ONE CANONICAL EXAMPLE: A common package.json might have these scripts: "scripts": { "start": "node server.js", "dev": "nodemon server.js", "test": "jest", "lint": "eslint ." }. Here, npm start runs the server. npm run dev runs it with nodemon for auto-restarts. npm test runs the Jest test runner. npm run lint checks the code style. Note that start and test are special and don't require the run keyword.

Read the original → docs.npmjs.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.