npm scripts minangka perintah sing ditetepake ing field scripts ing package.json sing dijalanake kanthi npm run <name>. Ngawur tugas proyek (start, build, test, lint) supaya kabeh tim lan CI nggunakake perintah sing padha. Lifecycle hooks minangka script spesial sing npm jalanake kanthi otomatis ing titik-titik tartamtu.
Nentukake lan jalanake scripts
{
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"build": "tsc && vite build",
"test": "vitest",
"lint": "eslint src",
"format": "prettier --write ."
}
}
npm run dev # any script
npm start # `start` and `test` have shortcuts (no "run" needed)
npm test
Scripts bisa ngrangkai perintah kanthi && (jalanake kanthi urut, mandheg yen ana gagal) lan nduweni akses menyang binari sing dipasang lokal (ing node_modules/.bin) tanpa jalur — dadi "test": "vitest" bisa jalan senadyan vitest ora global.
Pre lan post hooks (otomatis)
{
"scripts": {
"prebuild": "rimraf dist", // runs AUTOMATICALLY before "build"
"build": "tsc",
"postbuild": "echo done" // runs AUTOMATICALLY after "build"
}
}
npm kanthi otomatis jalanake pre<name> sadurunge lan post<name> sadurunge script apapun <name>. Dadi npm run build jalanake prebuild → build → postbuild kanthi urut — gampang kanggo tahap setup/cleanup.
Built-in lifecycle hooks
{
"scripts": {
"postinstall": "node setup.js", // runs after `npm install` completes
"prepare": "husky install" // runs after install (commonly sets up git hooks)
}
}
Hooks kaya postinstall lan prepare jalanake ing momen sing ditetepake ing lifecycle install — asring digunakake kanggo nyiyapake git hooks (husky) utawa ngompilake dependensi native. (Kanthi hati-hati: postinstall scripts ing dependensi uga dadi pertimbangan keamanan supply-chain.)
Ngluwarkake argument lan env vars
npm run test -- --watch # pass args to the script after --
NODE_ENV=production npm start # set an env var for the run
Alasan npm scripts tinimbang Makefile/global tools
✓ Self-documenting — `package.json` shows all available tasks
✓ Cross-platform-ish, no global installs needed (uses local node_modules/.bin)
✓ Standard across the JS ecosystem — every dev knows `npm run`
Apa sing penting
npm scripts minangka task runner standar kanggo proyek Node/JS — sing nglumpukake lan ndokumentasikake carane start, build, test, lan lint aplikasi, mesthekake kabeh wong (lan CI) jalanake perintah sing padha.
Ngrerteni komposisi script, automatic pre/post hooks (kanggo setup/cleanup), lan lifecycle hooks kaya postinstall/prepare nganti otomatisake alur kerja proyek kanthi resik.
Dadi lem tooling proyek lan muncul ing meh kabeh repositori Node.
