npm Scripts: Automating Everything
In a JavaScript project, package.json isn't just for dependencies—it's also a powerful Task Runner. You can define custom commands to automate your entire development and deployment workflow.
🏃 Standard Scripts
Most professional projects follow a convention for script names. This allows tools (and other developers) to interact with your project predictably.
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"build": "vite build",
"test": "jest",
"lint": "eslint ."
}npm start: Runs the production entry point.npm run dev: Starts the development server (usually with hot-reloading).npm run build: Compiles and minifies the code for production.npm test: Executes the test suite.
🪝 Lifecycle Hooks (pre & post)
npm allows you to run scripts automatically before or after another script by prefixing it with pre or post.
"scripts": {
"prebuild": "rm -rf dist/",
"build": "vite build",
"postbuild": "echo 'Build finished successfully!'"
}- When you run
npm run build, npm will executeprebuild, thenbuild, thenpostbuild. - Primary Use Case: Cleaning build folders, running linters before tests, or triggering notifications after a build.
🛠️ Cross-Platform Scripts
One common challenge in DevOps is that developers might use Windows while the production server uses Linux.
[!WARNING] Avoid Shell-Specific Commands Commands like
rm -rfwork on Linux/macOS but fail on standard Windows shells. Use libraries likerimraforcross-envto make your scripts universal.
"scripts": {
"clean": "rimraf dist/",
"start:prod": "cross-env NODE_ENV=production node server.js"
}💡 Practical masterclass: Chaining Commands
You can chain multiple commands together using standard shell operators:
&&: Run the second command ONLY if the first succeeds.&: Run both commands simultaneously (in the background).
"scripts": {
"deploy": "npm test && npm run build && node deploy.js"
}