Understanding npm Scripts
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.
Note: Run npm run (with no script name) to list every available script in the current project.
Warning: npm start and npm run start both work as a special case, but most other custom scripts need the explicit run keyword: npm run build, not npm build.
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 command in your terminal.
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).
Note: Check package.json's scripts section first when joining an unfamiliar project -- it tells you exactly how to run it.
Warning: Running npm run build when you meant to start the dev server will not open a live preview -- it just writes files to a dist/ or build/ folder and exits.
Example: Common Scripts You'll Use
npm run dev # local dev server
npm run build # production bundle
npm test # run test suite
⚠️ Run this command in your terminal.
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.
Note: Custom script names can be anything -- they're just labels mapped to a shell command.
Warning: A custom script name that collides with a built-in npm command name can behave unexpectedly -- keep names distinct and descriptive.
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 command in your terminal.
- 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: