Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

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 -y

The -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 dayjs

npm 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/2025

Scripts

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 start

Development 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
CommandWhat it does
npm init -yCreates package.json
npm install nameInstalls a package
npm installInstalls everything listed in package.json
npm uninstall nameRemoves a package
npm run nameRuns 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.

Thanks for reading!

Donate to the site — we work hard for you.