Advanced npm Scripts with Pre/Post Hooks
Automate build, test, and deployment workflows using npm scripts with lifecycle hooks, cross-platform commands, and script composition.
Prerequisites
- -Node.js and npm installed
Steps
Define common scripts
Set up build, test, and development scripts in package.json.
Add pre and post lifecycle hooks
Run tasks automatically before or after standard scripts.
Pre/post hooks run automatically. 'prebuild' runs before 'build', 'postbuild' runs after. This works for any script name.
Compose scripts with npm-run-all
Run multiple scripts in parallel or sequentially.
run-s runs scripts sequentially (stops on failure). run-p runs them in parallel.
Use environment variables in scripts
Pass configuration to scripts via environment variables.
Setting env vars inline like NODE_ENV=production works on macOS/Linux but not Windows. Use cross-env for cross-platform compatibility.
List and run available scripts
View all defined scripts and understand what is available.
Full Script
FAQ
Discussion
Loading comments...