npm and package.json
The bakery wants a photo carousel and a date picker for cake orders. You could write both from scratch, or use well-tested code other developers have already shared. Packages are that shared code, and a package manager downloads them, tracks them and keeps every teammate's copy the same. npm is the one that comes with Node.js.
The rule
package.jsonlists what the project needs; the package manager fetches it.
Start a project's manifest with:
npm init -yThis creates package.json, a small JSON file describing the project:
{
"name": "crumb-site",
"version": "1.0.0",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"flatpickr": "^4.6.13"
},
"devDependencies": {
"vite": "^5.4.0"
}
}Installing packages.
npm install flatpickr # needed by the site itself
npm install -D vite # needed only while developingnpm install <name>downloads the package from the npm registry, the big public library of packages, and adds it todependencies.-D(short for--save-dev) puts it underdevDependenciesinstead: tools you need for building and testing, but which the finished site does not run.- The code lands in a
node_modulesfolder, along with every package those packages depend on. That folder gets large quickly.
Recreating the setup. A teammate who clones the repository gets package.json but not node_modules, because node_modules belongs in .gitignore. They run one command:
npm installWith no name after it, npm install reads package.json and installs everything listed.
Scripts. The scripts section gives short names to common commands. npm run dev runs vite; npm run build runs vite build. A few names such as test and start also work without run. Scripts can use tools installed in node_modules directly, so nobody has to install them globally.
The shortcut
For every package, ask "Does the finished site need this to run in the visitor's browser?" Yes: a normal dependency. No, it only helps you build, test or check code: a dev dependency with -D.
Create the manifest
npm init -ywrites a starterpackage.json.
The trap is committing node_modules. It is huge, it can be rebuilt at any time, and some of its contents are specific to one operating system. A related habit to avoid is installing project tools globally with npm install -g. Different projects may need different versions, and a global install is invisible to teammates. Keep tools in devDependencies and run them through scripts.
Drills
Answer fast — trust the rule.
A linter only checks your code while you work. How should you install it?
A teammate has just cloned the project. Which command installs everything listed in package.json?
package.json has "scripts": { "build": "vite build" }. How do you run it?
Should node_modules be committed to Git?
Remember
package.jsonlists what the project needs; the package manager fetches it.- Needed by visitors: dependency. Only needed while building:
-D. - Trap: never commit
node_modules.
