Almost no Node project is written from scratch. npm is the registry and the command-line tool that installs the work other people have published.
Learning objectives
- Read and edit
package.json. - Install, remove and update dependencies.
- Tell
dependenciesanddevDependenciesapart. - Run project scripts and one-off binaries with
npx. - Keep generated folders out of Git.
1. package.json
npm init -y creates it:
{
"name": "date-dashboard",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"dependencies": {
"dayjs": "^1.11.10"
},
"devDependencies": {
"nodemon": "^3.0.2"
}
}
nameandversionidentify the package (lowercase, no spaces)."private": trueprevents accidentally publishing it."type": "module"switches.jsfiles to ES modules.scriptsare shortcuts run withnpm run <name>.
2. Installing packages
npm install dayjs # runtime dependency
npm install --save-dev nodemon # development only
npm install # install everything from package.json
npm uninstall dayjs
npm outdated
npm update
dependencies are needed when the app runs in production. devDependencies are tools used while building — test runners, linters, nodemon. A production install (npm ci --omit=dev) skips them, keeping images small.
package-lock.json records the exact resolved versions of the whole tree. Commit it: it is what makes installs reproducible.
3. npx
npx runs a package binary without installing it globally:
npx create-next-app@latest my-app
npx prettier --write .
Global installs (npm i -g) are best avoided — projects then depend on whatever version happens to be on the machine.
4. nodemon
Restarting the server by hand after every edit gets old. nodemon watches the folder:
npm install --save-dev nodemon
With the script above, npm run dev restarts on save. In newer Node versions, node --watch server.js does the same without a dependency.
5. Using a package
const dayjs = require("dayjs");
const now = dayjs();
console.log(now.format("YYYY-MM-DD HH:mm:ss"));
console.log(now.add(100, "day").format("YYYY-MM-DD"));
const birthday = dayjs("1995-03-20");
console.log(now.diff(birthday, "year"), "years old");
Read the package README for its API; most libraries follow the same install → require → call shape.
6. .gitignore
Never commit node_modules or secrets:
node_modules/
.env
dist/
.DS_Store
*.log
Anyone who clones the project runs npm install and gets the same tree from package-lock.json.
Common mistakes
- Committing
node_modules— thousands of files and platform-specific binaries. - Installing a build tool as a runtime dependency.
- Deleting
package-lock.jsonto "fix" an install problem; it is the only record of what actually worked. - Forgetting to add
.envto.gitignorebefore the first commit.
Practice
Build the date dashboard in the assignment. It is a real npm project: dependencies, scripts, a dev tool and a small CLI.