Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Installing packages

A package is a ready-made library published in the npm registry: for parsing Markdown, working with dates, sending email. npm install downloads a package into the project and records it in package.json, so another developer or a server can install the same libraries.

Installing a package

Blog posts are convenient to write in Markdown. The marked package turns Markdown into HTML. Install it from the blog folder:

npm install marked

Three things happen: the package is downloaded into the node_modules folder, a dependencies section appears in package.json, and a package-lock.json file appears next to it.

Importing it

A package from npm is imported by name, without ./ and without an extension:

// app.js
import { marked } from 'marked';
 
const html = marked.parse('# Hello\n\nThe first blog post.');
 
console.log(html);

node app.js prints HTML: <h1>Hello</h1> and a paragraph with the text. Node.js finds the package by name in the node_modules folder.

dependencies and devDependencies

Some packages are needed by the program while it runs, others only by you while developing: code formatters, linters, test libraries. The latter are installed with the -D flag:

npm install -D prettier
{
  "dependencies": {
    "marked": "^15.0.0"
  },
  "devDependencies": {
    "prettier": "^3.4.0"
  }
}

A server can install only the runtime packages — that is faster and safer. Your version numbers will be newer.

Versions

The ^ before a version allows updates that keep compatibility: ^15.0.0 allows 15.1.0 and 15.2.3, but not 16.0.0. The exact versions of all packages, nested ones included, are pinned in package-lock.json — thanks to it everyone on the project has the same set.

Main commands

CommandWhat it does
npm installInstalls everything listed in package.json
npm install markedAdds a package to dependencies
npm install -D prettierAdds a package to devDependencies
npm uninstall markedRemoves a package
npm outdatedShows outdated packages
npm ciInstalls exactly from package-lock.json

npm ci is used on servers and in automated checks, npm install while developing.

Common mistake

The node_modules folder must not go into Git: it holds tens of thousands of other people's files and is fully restored by npm install. Create a .gitignore file in the project root before the first commit:

node_modules
.env

package-lock.json, on the other hand, must be kept in Git.

Thanks for reading!

Donate to the site — we work hard for you.