npm, package.json and Scripts
npm installs packages - code that other people have shared - from npmjs.com. Your project's packages and settings live in package.json.
npm is the world's largest collection of open-source code. Instead of writing everything yourself - a web server, date handling, password hashing - you install well-tested packages. package.json records what your project needs so anyone can install the same setup with one command.
Example
mkdir shop-api && cd shop-api
npm init -y # creates package.json
npm install express # a package your app needs
npm install -D nodemon # -D: only needed while developingExample
{
"name": "shop-api",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "node --test"
},
"dependencies": { "express": "^5.1.0" },
"devDependencies": { "nodemon": "^3.1.9" }
}Useful commands
npm install- installs everything listed in package.json (after cloning a project)npm run dev- runs a script;npm startandnpm testwork withoutrunnpm uninstall express- removes a packagenpx some-tool- runs a tool without installing it globallynpm outdated/npm audit- find old or unsafe packages
node_modules and package-lock.json
node_modules/holds the downloaded packages. Never edit it, and never commit it - add it to.gitignore.package-lock.jsonrecords the exact versions installed. Do commit it, so everyone gets the same versions.
Version numbers
^5.1.0 means "5.1.0 or any newer 5.x". The three numbers are major.minor.patch: a major change may break your code; minor adds features; patch fixes bugs.
Before installing a package, check it's popular and maintained (weekly downloads, last update). Every package you add is code you're trusting.
Key points
- npm install adds packages; package.json lists them.
- Commit package-lock.json, not node_modules.
- Check a package is trusted and maintained before using it.
📝 Test yourself
1. Which file lists a project's packages and scripts?
2. Should you commit node_modules to Git?
3. Fill in the command to run the 'dev' script:
npm dev
