Understanding npm Scripts
{
"scripts": {
"scriptName": "command"
}
}
npm run scriptName
What the scripts Section Does
The scripts section of package.json defines named shortcuts for common commands, like "start": "vite" or "build": "vite build", so you type npm run build instead of the full underlying command.
Example: Listing and Running npm Scripts
$ npm run
Lifecycle scripts included in my-app:
dev
vite
build
vite build
preview
vite preview
$ npm run build
vite v5.0.0 building for production...
✓ 34 modules transformed.
dist/index.html
dist/assets/index-4f3a2b1c.js
⚠️ Run this in your own terminal or Node.js environment.
Common Scripts You'll Use
Nearly every React project ships with a dev/start script (runs the local dev server), a build script (creates the production bundle), and often a test script (runs the test suite).
Example: Common Scripts You'll Use
npm run dev # local dev server
npm run build # production bundle
npm test # run test suite
⚠️ Run this in your own terminal or Node.js environment.
Adding Your Own Script
You can add a custom entry to the scripts section yourself, like "lint": "eslint src", and then run it the same way with npm run lint.
Example: Adding Your Own Script
// package.json
{
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint src"
}
}
$ npm run lint
> [email protected] lint
> eslint src
src/App.jsx
12:7 warning 'count' is assigned a value but never used no-unused-vars
⚠️ Run this in your own terminal or Node.js environment.
- Running a custom script without the
runkeyword (works forstart/testbut not custom names). - Not checking the
scriptssection of package.json before assuming a command exists. - Overwriting a built-in script name (like
start) without realizing it changes default behavior.
- npm scripts are shortcuts defined in the
scriptssection of package.json. npm startandnpm testcan be run without the wordrun; custom scripts neednpm run <name>.- Common React scripts include start (dev server), build (production bundle), and test.
- You can add your own custom scripts for tasks like linting or formatting.
Not applicable -- npm scripts run in the terminal, not the browser.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: