Packages and npm
Many tasks have already been solved by someone: formatting dates, generating identifiers, working with spreadsheets. Ready-made code packaged for reuse is called a package, and npm (Node Package Manager) is a package manager: a program and a catalogue through which packages are downloaded and installed.
npm comes with Node.js — an environment that runs JavaScript outside the browser. The commands in this lesson are typed in a terminal, in the project folder.
package.json
A project starts with a package.json file — the project's passport with its name, version and list of packages. This command creates it:
npm init -yThe -y flag answers "yes" to every question and fills the file with default values.
Installing a package
A package is installed with npm install and its name. As an example, take dayjs, a library for working with dates:
npm install dayjsnpm downloads the package into the node_modules folder and records it in package.json. The packages a program needs to work are called dependencies:
{
"name": "my-app",
"type": "module",
"dependencies": {
"dayjs": "^1.11.13"
}
}The "type": "module" field lets you write import and export in Node.js.
Using a package
An installed package is imported by its name — without ./ and without an extension. Node.js finds it in node_modules by itself:
import dayjs from 'dayjs';
const date = dayjs('2025-03-08').format('MM/DD/YYYY');
console.log(date); // 03/08/2025Scripts
The scripts field of package.json holds the project's commands, so you do not have to type them out in full every time:
{
"scripts": {
"start": "node main.js"
}
}You run them with npm run and the script's name:
npm run startDevelopment dependencies
Some packages are needed only by the programmer: for tests, code checks, building. They are installed with the --save-dev flag and go into a separate devDependencies section:
npm install --save-dev prettier| Command | What it does |
|---|---|
npm init -y | Creates package.json |
npm install name | Installs a package |
npm install | Installs everything listed in package.json |
npm uninstall name | Removes a package |
npm run name | Runs a script |
Package versions
^1.11.13 means "version 1.11.13 or newer, but within 1.x": npm may install fixes, but not version 2, which could break things. npm records the exact installed versions in the package-lock.json file — it is kept with the project so that everyone has the same versions.
Common mistake
Committing the node_modules folder to a repository or sending it along with the project. It weighs hundreds of megabytes and is restored with a single npm install from the list in package.json. Add node_modules to the .gitignore file, and after cloning someone else's project, run npm install first.