🛠️ Custom Scripts with npm run
You can define your own shortcuts using the scripts section.
"scripts": {
"start": "node index.js",
"dev": "nodemon app.js"
}Then run:
npm run dev💡 This helps you avoid long terminal commands every time.
Creating Custom npm Scripts (with npm run)
Custom scripts let you define shortcuts for repetitive tasks like running your app, testing code, or checking for linting errors.
⚙️ Basic Scripts
Inside your package.json, add a scripts section:
"scripts": {
"start": "node index.js",
"dev": "nodemon app.js"
}You can now run them like this:
npm start # instead of 'node index.js'
npm run dev # instead of 'nodemon app.js'🧪 Testing Script
If you're using Jest, Mocha, or another test runner:
"scripts": {
"test": "jest"
}Or for Mocha:
"scripts": {
"test": "mocha"
}
✅ Run tests with:
npm test
🧼 Linting Script (ESLint)
If you're using ESLint to check code quality:
"scripts": {
"lint": "eslint ."
}✅ Run lint check with:
npm run lintYou can also auto-fix issues with:
"scripts": {
"lint:fix": "eslint . --fix"
}✅ Auto-fix linting issues:
npm run lint:fix🎨 Format Code (Prettier)
If you're using Prettier:
"scripts": {
"format": "prettier --write ."
}✅ Format all files:
npm run formatChaining Scripts
You can chain multiple scripts using &&:
"scripts": {
"check": "npm run lint && npm test"
}✅ This will run both the linter and test suite:
npm run check✅ Summary Table
Task | Script | Command |
|---|---|---|
Run app |
|
|
Dev server |
|
|
Run tests |
|
|
Lint check |
|
|
Lint fix |
|
|
Format code |
|
|
Chain scripts |
|
|
Sample File
{
"name": "my-app",
"version": "1.0.0",
"description": "Sample package.json with custom npm scripts",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon app.js",
"test": "jest",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"check": "npm run lint && npm test"
},
"devDependencies": {
"nodemon": "^3.0.0",
"jest": "^29.0.0",
"eslint": "^9.0.0",
"prettier": "^3.0.0"
}
}