Introduction to npm-run-script
The npm run-script
command is a powerful tool in the Node.js ecosystem for managing and automating tasks in an efficient manner. By leveraging npm scripts, developers can streamline their workflows, decrease manual effort, and maintain clean and organized codebases. In this comprehensive guide, we will explore dozens of useful APIs provided by npm scripts, and demonstrate their utilization with practical examples.
Basic npm Scripts
Let’s start with the basics of creating scripts in your package.json
file:
{ "name": "my-app", "version": "1.0.0", "scripts": { "start": "node index.js", "test": "mocha" } }
API Examples with npm Scripts
Running a Script
Use the following command to run a defined script:
npm run start
Pre and Post Hooks
Define pre and post hooks for scripts:
{ "scripts": { "prestart": "echo 'Starting application...'", "start": "node index.js", "poststart": "echo 'Application started.'" } }
Script Execution with Arguments
Pass arguments to npm scripts:
npm run myscript -- --arg1=value1 --arg2=value2
Parallel and Sequential Script Execution
Run scripts sequentially:
{ "scripts": { "build": "npm run clean && npm run compile" } }
Run scripts in parallel:
{ "scripts": { "build": "npm-run-all --parallel clean compile" } }
Environment Variables
Define and use environment variables in scripts:
{ "scripts": { "start": "NODE_ENV=production node index.js" } }
Shortcuts for Lifecycle Scripts
Use short-cut commands for lifecycle scripts:
npm start npm test
Running Binary Executables
Run binaries installed locally:
{ "scripts": { "lint": "eslint ." } }
Example App Using npm Scripts
Here is an example of a simple Node.js application that leverages npm scripts for various tasks:
{ "name": "example-app", "version": "1.0.0", "scripts": { "clean": "rm -rf dist", "compile": "babel src -d dist", "build": "npm run clean && npm run compile", "start": "node dist/index.js", "test": "jest" }, "devDependencies": { "babel-cli": "^6.26.0", "jest": "^24.9.0" }, "dependencies": { "express": "^4.17.1" } }
In this example, we have defined scripts for cleaning the dist
directory, compiling the source code, building the project, starting the server, and running tests. This setup demonstrates how npm scripts can be utilized to manage different aspects of the development workflow effectively.
By mastering the usage of npm scripts, you can greatly enhance your productivity and maintain a well-structured project.
Hash: 1414c2d93afe61f056cf9d7ac1165801f0a6f07c479caf40c223149c7be4ff4e