What are npm scripts and how do you run them?
Scripts are named shell commands in the scripts field of package.json. Run them with npm run name; start and test also work as npm start and npm test. Local binaries in node_modules/.bin are on the PATH automatically.
Explain it simply
Scripts are shortcuts. Instead of remembering node --watch src/index.js or a long test command, you give it a short name once and everyone on the team runs the same thing.
Example
{
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js",
"test": "node --test",
"lint": "eslint .",
"prebuild": "rm -rf dist",
"build": "tsc"
}
}npm start # same as npm run start
npm test # same as npm run test
npm run dev # custom names need "run"
npm run build -- --pretty # arguments after -- go to the scriptUseful details:
npm runwith no name lists all scripts.- A script named
prebuildruns automatically beforebuild, andpostbuildafter it. - Tools installed locally, like
eslint, work inside scripts without a global install because npm addsnode_modules/.binto the PATH.
What to say in the interview
"Scripts live in package.json and are run with npm run. start and test have shortcuts, pre and post hooks run around a script, and local binaries are available automatically, so the team does not need global installs."
Common mistakes
- Typing
npm devinstead ofnpm run dev. - Installing tools globally and having the project break on another machine.