What is npx, and how do npm scripts work?
2 minbeginnernodejsnpmnpxscriptstooling
Quick Answer
`npx` runs a package's binary without installing it globally — it uses a local `node_modules/.bin` binary or downloads the package temporarily. npm scripts are named commands in package.json's `scripts` block, run with `npm run <name>`, with access to `node_modules/.bin` on the PATH.
Detailed Answer
Answer:
npm scripts:
Defined under scripts in package.json and run via npm run <name>:
"scripts": {
"start": "node index.js",
"dev": "nodemon src/index.js",
"test": "jest",
"lint": "eslint src",
"build": "tsc"
}
- Run with
npm run dev.startandtestare special and also work asnpm start/npm test. - During a script,
node_modules/.binis added toPATH, so you can call locally-installed tools (jest,eslint,tsc) by name without a global install. - Lifecycle hooks: a script named
pre<name>runs before, andpost<name>runs after (e.g.,pretestruns beforetest).
npx:
npx executes a package binary without a permanent global install:
npx create-react-app my-app # download + run a scaffolder once
npx eslint . # run the locally installed eslint
npx cowsay hello # try a tool without installing it
Resolution order: a matching binary in the local node_modules/.bin first, otherwise npx downloads the package to a temporary cache and runs it.
Why it matters:
- Avoids polluting the global namespace and version drift from globally installed CLIs.
- Ensures you run the project's pinned version of a tool rather than whatever is installed globally.