npm & package.json
npm: Node's package manager
npm installs packages (libraries) from the npm registry, which has millions of them.
npm init -y # create package.json
npm install dayjs # add a dependency
npm install -D vite # add a dev-only dependency
npm uninstall dayjs
npm run dev # run a script from package.json
package.json
{
"name": "my-app",
"type": "module",
"scripts": { "dev": "vite", "build": "vite build" },
"dependencies": { "dayjs": "^1.11.10" },
"devDependencies": { "vite": "^5.0.0" }
}
- dependencies are needed when the app runs; devDependencies are only for building and testing.
scriptsare shortcuts run withnpm run <name>.
Versions (semver: MAJOR.MINOR.PATCH)
^1.11.10allows updates up to (but not including) 2.0.0.~1.11.10allows only patch updates (1.11.x).package-lock.jsonrecords the exact installed versions. Commit it, so everyone installs the same thing.
node_modules
The folder where packages are installed. It's huge: never commit it (add it to .gitignore); npm install recreates it.
Tips
- Check a package's downloads, last update and size before adding it.
npm auditlists known security issues.- Alternatives: pnpm (faster, saves disk space), yarn, bun.
Example
# Start a project
mkdir my-app && cd my-app
npm init -y
# Add packages
npm install dayjs
npm install -D vite
# .gitignore
echo "node_modules/" >> .gitignore
# package.json → "scripts": { "dev": "vite", "build": "vite build" }
npm run dev
# 💻 Terminal commands — run them on a computer with Node.js installed