NPM Scripts & Lifecycle Hooks
Intermediatev1.0.0
Master npm scripts for task automation — custom scripts, lifecycle hooks, cross-platform commands, script composition, and replacing Makefiles with package.json scripts.
Content
Overview
NPM scripts are the standard way to automate tasks in JavaScript projects — building, testing, linting, deploying, and more. They replace Makefiles, shell scripts, and task runners with a unified, portable interface.
Why This Matters
- -Universal — every JS developer knows npm run
- -No extra tools — built into npm, no Gulp/Grunt/Make needed
- -Composable — chain scripts with pre/post hooks and operators
- -Discoverable —
npm runlists all available scripts
Script Composition
Lifecycle Hooks
Cross-Platform Commands
Passing Arguments
Best Practices
- -Use
validatescript that runs all checks (typecheck + lint + test) - -Use
preparehook for post-install setup (husky, build steps) - -Use
prepublishOnlyto validate and build before publishing - -Keep scripts short — extract complex logic to shell scripts
- -Use cross-platform packages (rimraf, cross-env) for portability
- -Add descriptions with comments in a separate scripts section
Common Mistakes
- -Using platform-specific commands (rm -rf on Windows fails)
- -Forgetting
--when passing arguments to scripts - -Not using prepublishOnly to ensure builds before publish
- -Complex multi-line scripts that should be separate files
FAQ
Discussion
Loading comments...