What are npm scripts and how do you run them?
BeginnerHands-onNode.js builds (npm, package.json)
Answer
Short answer
npm scripts are named commands in the "scripts" section of package.json. npm start and npm test run the start and test scripts; any other script runs with npm run <name>. Scripts are how a project tells you how to build, test, lint and start it — they're the first thing a DevOps engineer reads.
Example
"scripts": {
"start": "node dist/server.js",
"dev": "nodemon src/server.ts",
"build": "tsc -p tsconfig.json",
"test": "jest --ci --coverage",
"lint": "eslint .",
"migrate": "knex migrate:latest"
}
npm start # node dist/server.js
npm test # jest --ci --coverage
npm run build
npm run lint
npm run migrate
Handy details
- Scripts can call binaries from
node_modules/.bindirectly (jest,tsc) without global installs. - pre/post hooks: a
prebuildscript runs automatically beforebuild. - Pass extra arguments with
--:npm test -- --runInBand.
In the pipeline
- run: npm ci
- run: npm run lint
- run: npm test
- run: npm run build
What to say in the interview
"I read the scripts section first — it tells me exactly how the team builds and runs the app. The pipeline then just calls npm ci, npm run lint, npm test and npm run build, so CI does the same thing developers do."
More on Node.js builds (npm, package.json)
What is package.json and what does it contain?BeginnerHow do you build and run a Node.js application?BeginnerWhat is the difference between npm install and npm ci?BeginnerWhy must package-lock.json be committed to Git?BeginnerWhat is the difference between dependencies and devDependencies?BeginnerWhat do the ^ and ~ symbols mean in package.json versions?Beginner