Scripts: Automating Tasks
What you'll learn: How to use the scripts field in package.json to create custom commands that automate your build, test, and deployment workflows.
The Automation Hub
You've already learned that package.json has a scripts field where you can define commands. Now it's time to harness this as your project's automation hub. Think of it as creating shortcuts for repetitive terminal commands—instead of typing long, complex commands every time, you define them once and run them with simple names.
Beyond Basic Scripts
While you can run any script with npm run <name>, the real power comes from designing a complete workflow:
{
"scripts": {
"build": "webpack --mode production",
"build:dev": "webpack --mode development",
"test": "jest",
"test:watch": "jest --watch",
"lint": "eslint src/",
"lint:fix": "eslint src/ --fix",
"clean": "rm -rf dist/",
"prebuild": "npm run clean",
"deploy": "npm run build && aws s3 sync dist/ s3://my-bucket"
}
}
Workflow Patterns
Namespacing with colons: Group related tasks like build:dev and build:prod for clarity.
Pre and post hooks: prebuild runs automatically before build, posttest after test.
Composition: Chain commands with && for sequential execution, or use npm run build && npm run deploy to create pipelines.
Cross-project consistency: Your team runs npm test whether you're using Jest, Mocha, or any other tool—the implementation is hidden behind the interface.
The Real Win
Scripts turn your package.json into executable documentation. New developers don't need to memorize commands or search through READMEs—they run npm run to see available tasks.
Key Takeaway: The scripts field transforms package.json into a command center, standardizing how your team builds, tests, and deploys, regardless of the underlying tools.