0% found this document useful (0 votes)
13 views29 pages

Package Manager: Laying Out The Basics

The document discusses the evolution of package management in web development, highlighting the importance of tools like npm and Yarn for managing project dependencies. It explains the features and installation processes of both package managers, along with the structure and purpose of the package.json file. Additionally, it covers essential npm commands for initializing projects and installing packages, as well as the distinction between dependencies and devDependencies.

Uploaded by

Prabin Magar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views29 pages

Package Manager: Laying Out The Basics

The document discusses the evolution of package management in web development, highlighting the importance of tools like npm and Yarn for managing project dependencies. It explains the features and installation processes of both package managers, along with the structure and purpose of the package.json file. Additionally, it covers essential npm commands for initializing projects and installing packages, as well as the distinction between dependencies and devDependencies.

Uploaded by

Prabin Magar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Laying Out the Basics

Back in the good old days, a simple text editor was enough for developers to create and manage
the large part of their projects. But since then, the Web has changed drastically. Nowadays, it’s
common for even a fairly simple project to have hundreds or thousands of scripts, with complex
nested dependencies, which are simply impossible to manage without some kind of automated tool.
And this is the place where package managers come into play.

A package manager is a tool that automatically handles a project’s dependencies in a variety of


ways. For example, with the help of a package manager we can install, uninstall, update, and
upgrade packages, configure project settings, run scripts, and so on. All the hard and tedious work
is done by the package manager, leaving to us only the fun part — the coding itself.
Introduction to NPM & Yarn

Npm stands for Node Package Manager. It was released back in 2010, beginning a new era in web
development. Until then, the project dependencies were downloaded and managed manually. npm
was the magic wand that pushed the Web to the next level. It is a package manager for the Node
JavaScript platform.

Npm is known as the world’s largest software registry. Open-source developers all over the world
use npm to publish and share their source code.

Npm consists of three components:

 The website allows you to find third-party packages, set up profiles, and manage your packages.
 The command-line interface or npm CLI that runs from a terminal to allow you to interact with
npm.
 The registry is a large public database of JavaScript code.

However, when most people talk about npm, they usually mean the second one — the CLI tool. It
ships as a default package manager with each fresh Node installation. This means you can start
using it right away.

Yarn stands for Yet Another Resource Negotiator. The Yarn package manager is an alternative to
npm, released by Facebook in October 2016. The original goal of Yarn was to deal with npm
drawbacks, such as performance and security issues. Yarn was quickly positioned as a safe, fast,
and reliable JavaScript dependency management tool.

Nowadays, both package managers are neck and neck in the package management race, offering
similar features and capabilities. But there are still several differences that help to determine which
we choose to use.

Yarn is a package manager for [Link] that focuses on speed, security, and consistency. It was
originally created to address some issues with the popular NPM package manager. Though the two
package managers have since converged in terms of performance and features, Yarn remains
popular, especially in the world of React development.

Some of the unique features of Yarn are:

 A per-project caching mechanism, that can greatly speed up subsequent installs and builds
 Consistent, deterministic installs that guarantee the structure of installed libraries are always
the same
 Checksum testing of all packages to verify their integrity
 “Workspaces”, which facilitate using Yarn in a monorepo (multiple projects developed in a single
source code repository)
Yarn vs npm: an Installation Comparison

Installing the package managers themselves

As noted above, npm comes preinstalled with Node, so there’s no need to install npm manually.

In contrast, Yarn needs to be installed explicitly. First, we need to install Yarn globally:

npm install -g yarn

Then, we can use it on a per-project basis by setting the desired version inside our project. We do
that by running the yarn set version command in the project’s root directory:

yarn set version berry

In this case, berry is the version we want to set.

If we want to update to the latest version, we run this:

yarn set version latest

With Yarn we can use a different version for each project.

Installing project dependencies

Now, let’s see how project dependencies are installed.

When we run npm install, the dependencies are installed sequentially, one after another. The
output logs in the terminal are informative but a bit hard to read.

To install the packages with Yarn, we run the yarn command. Yarn installs packages in parallel,
which is one of the reasons it’s quicker than npm. If you’re using Yarn 1, you’ll see that the yarn
output logs are clean, visually distinguishable and brief. They’re also ordered in a tree form for easy
comprehension. But this is changed in versions 2 and 3, where the logs aren’t so intuitive and
human-readable.

So far, we’ve seen that npm and Yarn have different commands for installing packages. In the next
section, we’ll explore more commands.

An Absolute Beginner's Guide to [Link]

As a general rule, any project that's using [Link] will need to have a [Link] file. What is
a [Link] file?

At its simplest, a [Link] file can be described as a manifest of your project that includes the
packages and applications it depends on, information about its unique source control, and specific
metadata like the project's name, description, and author.

Let's break down the core parts of a typical [Link] file:

Specific Metadata: name, version, description, license, and keywords

Inside a [Link], you'll almost always find metadata specific to the project - no matter if it's a
web application, [Link] module, or even just a plain JavaScirpt library. This metadata helps identify
the project and acts as a baseline for users and contributors to get information about the project.
Here's an example of how these fields would look in a [Link] file:

{
"name": "metaverse", // The name of your project
"version": "0.92.12", // The version of your project
"description": "The Metaverse virtual reality. The final outcome of all virtual
worlds, augmented reality, and the Internet.", // The description of your project
"main": "[Link]"
"license": "MIT" // The license of your project
}

A [Link] file is always structured in the JSON format, which allows it to be easily read as
metadata and parsed by machines.

If needing to format a [Link] file manually to get your project up and running seems a bit
daunting, there's a handy command that will automatically generate a base [Link] file for
you - if you'd like to learn how to use it, take a peek at the npm init instructions below!

Understanding and Managing Your Project's


Dependencies: dependencies and devDepenendcies in your [Link]

The other majorly important aspect of a [Link] is that it contains a collection of any given
project's dependencies. These dependencies are the modules that the project relies on to function
properly.

Having dependencies in your project's [Link] allows the project to install the versions of the
modules it depends on. By running an install command inside of a project, you can install all of the
dependencies that are listed in the project's [Link] - meaning they don't have to be (and
almost never should be) bundled with the project itself.

Second, it allows the separation of dependencies that are needed for production and dependencies
that are needed for development. In production, you're likely not going to need a tool to watch your
CSS files for changes and refresh the app when they change. But in both production and
development, you'll want to have the modules that enable what you're trying to accomplish with
your project - things like your web framework, API tools, and code utilities.

What would a project's [Link] look like with dependencies and devDependencies? Let's
expand on the previous example of a [Link] to include some.

{
"name": "metaverse",
"version": "0.92.12",
"description": "The Metaverse virtual reality. The final outcome of all virtual
worlds, augmented reality, and the Internet.",
"main": "[Link]"
"license": "MIT",
"devDependencies": {
"mocha": "~3.1",
"native-hello-world": "^1.0.0",
"should": "~3.3",
"sinon": "~1.9"
},
"dependencies": {
"fill-keys": "^1.0.2",
"module-not-found-error": "^1.0.0",
"resolve": "~1.1.7"
}
}

One key difference between the dependencies and the other common parts of a [Link] is
that they're both objects, with multiple key/value pairs. Every key in
both dependencies and devDependencies is a name of a package, and every value is the version
range that's acceptable to install (according to Semantic Versioning - to learn more about Semantic
Versioning, also known as semver, check out our primer on semver).

The Essential npm Commands

When using npm, you're most likely going to be using the command line tool for the majority of
your interactions. As such, here's a detailed rundown of the commands that you'll encounter and
need to use most frequently.

Using npm init to Initialize a Project

The npm init command is a step-by-step tool to scaffold out your project. It will prompt you for input
for a few aspects of the project in the following order:

 The project's name,


 The project's initial version,
 The project's description,
 The project's entry point (meaning the project's main file),
 The project's test command (to trigger testing with something like Standard)
 The project's git repository (where the project source can be found)
 The project's keywords (basically, tags related to the project)
 The project's license (this defaults to ISC - most open-source [Link] projects are MIT)

It's worth noting that if you're content with the suggestion that the npm init command provides
next to the prompt, you can simply hit Return or Enter to accept the suggestion and move on to the
next prompt.

Once you run through the npm init steps above, a [Link] file will be generated and placed in
the current directory. If you run it in a directory that's not exclusively for your project, don't worry!
Generating a [Link] doesn't really do anything, other than create a [Link] file. You
can either move the [Link] file to a directory that's dedicated to your project, or you can
create an entirely new one in such a directory.

HOW TO USE NPM INIT:

npm init # This will trigger the initialization

Using npm init --yes to Instantly Initialize a Project

If you want to get on to building your project, and don't want to spend the (albeit brief) time
answering the prompts that come from npm init, you can use the --yes flag on the npm
init command to automatically populate all options with the default npm init values.

Note: You can configure what these default values are with the npm configuration - that's a more
advanced topic, and outside the scope of this beginner's guide to npm.

USAGE: npm init --yes # This will trigger automatically populated initialization.

Install Modules with npm install


Installing modules from npm is one of the most basic things you should learn to do when getting
started with npm. As you dive deeper, you'll begin to learn some variations on installing modules,
but here's the very core of what you need to know to install a standalone module into the current
directory:

npm install <module>

In the above command, you'd replace <module> with the name of the module you want to install.
For example, if you want to install Express (the most used and most well-known [Link] web
framework), you could run the following command:

npm install express

The above command will install the express module into /node_modules in the current directory.
Whenever you install a module from npm, it will be installed into the node_modules folder.

In addition to triggering an install of a single module, you can actually trigger the installation
of all modules that are listed as dependencies and devDependencies in the [Link] in the
current directory. To do so, you'll simply need to run the command itself:

npm install

Once you run this, npm will begin the installation process of all of the current project's
dependencies.

As an aside, one thing to note is that there's an alias for npm install that you may see in the wild
when working with modules from the ecosystem. The alias is npm i, where i takes the place
of install.

This seemingly minor alias is a small gotcha for beginners - including myself, several times when I
was learning - to the [Link] and npm ecosystems, as there's not a standardized, single way that
module creators and maintainers will instruct on how to install their module.

USAGE:

npm install <module> # Where <module> is the name of the module you want to install
npm i <module> # Where <module> is the name of the module you want to install -
using the i alias for installation

-------

To find the npm CLI on your computer, you run the npm command from a terminal: npm

For example, the following command will display the current npm version on your system: npm -v

What can you do with npm? npm allows you to install a new package from the registry. This is
what you will do most of the time with npm. On top of this, npm allows you to discover and publish
your new node packages.

[Link]

In general, every npm project has a file called [Link] located in the root directory.
The [Link] is a plain text file that contains important information that npm uses to identify
the project and handle dependencies. To create the [Link] file, you go to the root directory
of the project and execute the following command:

npm init
When you run the npm init command, it will prompt you for the project information including:

 Package name
 Version
 Test command
 Git repository
 Keywords
 Author
 License

If you hit Return or Enter, it will accept the default values and move on to the next prompt.

If you want to use default options, you use the following command: npm init --yes

Later, you can change the default values in the [Link].

Install a new package

To install a new package, you use the following npm install command: npm install
<package_name>

In this command, you place the package name after the npm install keywords. To find packages,
you go to the npm website and search for them.

For example, if you want to install the express package, you can run the following command:

npm install express

Note that express is a fast web framework for Node.

Once the installation is completed, you will see a new directory called /node_modules created under
the root of the project. All the new modules that you install will be placed in this directory.

If you expand the /node_modules directory, you will see that npm installed not only express but
also the dependencies of express, and dependencies of these dependencies, and so on.

If you open the [Link] file in the root of the project, you will also find that
the dependencies section is updated, which includes the express package like this:

"dependencies": {
"express": "^4.17.1"
}

In general, any new package that you install will be listed in the dependencies section. In this
example, the dependencies include the express package with version 4.17.1. Notice that Npm
follows the semantic versioning specification.

To save some typing, you can use a shorter version of the npm install command: npm i
<package_name>

In this command, i stands for install.

Install a package as a development dependency

Sometimes, you may want to install a package that runs only on the development environment. For
example, you may want to install a package that logs HTTP requests such as the morgan package.

To do this, you the npm install command with the --save-dev option with the following syntax:
npm install <package_name> --save-dev

For instance: npm install morgan --save-dev

This command will download and install the morgan package. In addition, it adds a new section to
the [Link] file called devDependencies like this:

"devDependencies": {
"morgan": "^1.10.0"
}

Basically, the devDependencies should contain packages that you use during development. These
packages are necessary only while you are developing your application.

On the other hand, the dependencies should contain packages on which your application will
depend. In other words, without these dependencies packages, your application will not work.

Also, you can execute the npm install command to download and install all packages listed on
the dependencies and devDependencies section: npm install

Install a package globally on your system

To install a package globally on your system, you use the following command: npm install
<package_name> --global

Or in short: npm i <package_name> -g

Generally, you install a package globally when you want to use it in your command line or shell. If
you want a package that you will include in your application, you should install it locally.

Yarn vs Npm Detail

How to check npm version?

Check your npm version by running this command.

npm --version

How to install Yarn?

Yarn can be installed through the command line of your terminal. I like to use the integrated
terminal of VSCode for this.

npm install --global yarn

How to check Yarn version?

Check Yarn version by running this command.

yarn --version

Yarn vs Npm Lock file

To make it consistent across all environments, when a package manager modifies the
node_modules folder or the [Link] file, it stores all the versions of the packages inside a
special lock file. This lock file is auto-generated and managed by the package manager.

For npm, this file is called [Link].


For yarn, this file is called [Link].

This file is intended to be committed inside the repository of your project.

DO NOT DELETE IT.

It is advised not to use both yarn and npm because this can create dependency conflicts. When it
comes to Yarn, Yarn makes it easy to switch from npm, because it can use [Link]
natively to import dependencies without external libraries.

Yarn vs Npm Commands

Both Yarn and Npm provide a rich CLI that will help you manage your dependencies and publish
your packages. Here are a few of those commands.

Yarn commands

Command Description
yarn init Initializes the development of your package.
yarn install Installs all the dependencies defined in your [Link] file.
yarn add <package> Adds a package to use in your current package.
yarn remove Removes a package from your current package.
<package>
yarn publish Publishes your package to a registry.
yarn why <package> Display the reason why a package is needed.
yarn licenses ls Allows you to inspect the licenses of your dependencies
yarn outdated Checks for outdated package dependencies.

Npm commands

Command Description
npm init Initializes the development of your package.
npm install Installs all the dependencies defined in your [Link] file.
npm install Adds a package to use in your current package.
<package>
npm uninstall Removes a package from your current package.
<package>
npm publish Publishes your package to a registry.
npm outdated Checks for outdated package dependencies.

Yarn vs Npm commands difference

As you can see, both yarn and npm have a lot of the same commands. The two big differences are
the commands to add and to remove a package.

 Add a package: yarn add <package> vs npm install <package>.


 Remove a package: yarn remove <package> vs npm uninstall <package>.
Also, Yarn supports some commands that npm doesn't:

 yarn why
 yarn licenses ls.

Yarn vs Npm Adding a package

How do you add a package in Yarn?

Add a package with yarn by running this command.

yarn add <package>

How do you add a package in npm?

Add a package with npm by running this command.

npm install <package>

Yarn vs Npm Dev Dependencies Packages

How do you add a dev dependency package in Yarn?

Add a package as a dev dependency with yarn by running this command.

yarn add <package> --dev

How do you add a dev dependency package in npm?

Add a package as a dev dependency with npm by running this command.

npm install <package> --save-dev

You will notice very soon, that node_modules is a very heavy folder. This is completely normal.

Yarn vs Npm Global Packages

To run those commands you may need to have administrator privileges.


How do you add a global package in Yarn?

Add a global package with yarn by running this command.

yarn global add <package>

How do you add a global package in npm?

Add a global package with npm by running this command.

npm install -g <package>

Yarn vs Npm Removing a package

Be careful not to remove something you need.

How do you remove a package in Yarn?

Remove a package with yarn by running this command.

yarn remove <package>

How do you remove a package in npm?

Remove a package with npm by running this command.

npm uninstall <package>

Yarn vs Npm Outdated Packages

How do you search for outdated packages in Yarn?

Search for outdated packages with yarn by running this command.

yarn outdated

How do you search for outdated packages in npm?

Search for outdated packages with npm by running this command.

npm outdated

Here is the output of this command when I ran it on this website:

$ yarn outdated
info Color legend :
"<red>" : Major Update backward-incompatible updates
"<yellow>" : Minor Update backward-compatible features
"<green>" : Patch Update backward-compatible bug fixes
Package Current Wanted Latest Package Type URL
@types/react 17.0.34 17.0.35 17.0.35 devDependencies
[Link]
eslint-config-next 12.0.3 12.0.3 12.0.4 devDependencies
[Link]
next 12.0.3 12.0.3 12.0.4 dependencies [Link]

If a package is red, this means the dependency had a breaking change so you will need to update it
manually.
Yarn vs Npm Updating a package

How do you update an outdated package in Yarn?

Update all outdated packages with yarn by running this command.

yarn upgrade

Update a specific package with yarn by running this command.

yarn upgrade <package>@latest

How do you update an outdated package in npm?

Update all outdated packages with npm by running this command.

npm update

Update a specific package with npm by running this command.

npm update <package>@latest

Comparing npm and Yarn Commands

npm and Yarn share many commands, but there are also many non-identical commands. Let’s first
explore some of the identical commands:

 npm init | yarn init: create a new package


 npm run | yarn run: run a script defined in the [Link]
 npm test | yarn test: test a package
 npm publish | yarn publish: publish a package
 npm cache clean | yarn cache clean: remove all data from the cache folder

These commands make switching between two managers easy, but there are some non-identical
commands that can cause confusion. Let’s see what they are in the next list:

 npm install | yarn: install dependencies


 npm install [package] | yarn add [package]: install a package
 npm install --save-dev [package] | yarn add - -dev [package]: install a package as a
development dependency
 npm uninstall [package] | yarn remove [package]: uninstall a package
 npm uninstall --save-dev [package] | yarn remove [package]: uninstall a development
dependency package
 npm update | yarn upgrade: update the dependencies
 npm update [package] | yarn upgrade [package]: update a package

Yarn has also some unique commands which don’t have npm equivalents. For example,
the why command displays the reason why a package is needed: it may be a dependency, a native
module, or a project dependency.

Commands - The table below provides an overview of some of the most frequently used
commands for NPM and Yarn:

Command NPM Yarn


Initialize a project npm init yarn init
Run tests for the current npm test yarn test
Command NPM Yarn
package
Check for outdated
npm outdated yarn outdated
packages
Publish a package npm publish yarn publish
Run a script npm run yarn run
Manage local package
npm cache clean yarn cache clean
cache
Log in or out npm login/logout yarn login/logout
Install dependencies npm install yarn
Install packages npm install [package name] yarn add [package name]
Uninstall packages npm uninstall [package name] yarn remove [package name]
Update manager npm update yarn upgrade
yarn upgrade [package
Update packages npm update [package name]
name]
npm install --global [package yarn global add [package
Install packages globally
name] name]
npm uninstall --global [package yarn global remove
Uninstall packages globally
name] [package name]
Interactive dependency
npm run upgrade-interactive yarn upgrade-interactive
update
Run package remotely yarn dlx
Check licenses yarn licenses ls

Yarn vs npm: Speed and Performance

Whenever Yarn or npm need to install a package, they carry out a series of tasks. In npm, these
tasks are executed per package and sequentially, meaning it will wait for a package to be fully
installed before moving on to the next. In contrast, Yarn executes these tasks in parallel, increasing
performance.

While both managers offers caching mechanisms, Yarn seems to do it a bit better. By implementing
a zero-install paradigm, as we’ll see in the features comparison section, it’s capable of installing
packages almost in no time. It caches every package and saves it on the disk, so in the next
installation of this package you don’t even need to have an internet connection, because the
package is installed offline from the disk.

Even though Yarn has some advantages, the speeds of Yarn and npm, in their last versions, are
pretty comparable. So we can’t define a clean winner here.

Yarn vs npm: a Feature Comparison

Just as with commands, some features are shared by npm and Yarn, while there are also some
differences. Let’s first explore the common features these two package managers share.

Generating a Lock File


In [Link], the file where both npm and Yarn keep track of the project’s dependencies,
version numbers aren’t always exact. Instead, you can define a range of versions. This way, you
can choose a specific major and minor version of a package, but allow npm to install the latest
patch that might fix some bugs.

In an ideal world of semantic versioning, patched releases won’t include any breaking changes. But
unfortunately, this isn’t always the case. The strategy employed by npm may result in two
machines ending up with the same [Link] file, but having different versions of a package
installed — which will possibly introduce bugs.

To avoid package version mismatches, an exact installed version is pinned down in a package lock
file. Every time a module is added, npm and Yarn create (or update) a package-
[Link] and [Link] file respectively. This way, you can guarantee another machine installs the
exact same package, while still having a range of allowed versions defined in [Link].

Using workspaces - Workspaces allow you to have one monorepo to manage the dependencies
across multiple projects. This means you have a single, top-level root package that has multiple
child packages called workspaces.

Running scripts remotely

The npx command is used to run scripts from ./node_modules/.bin. It also allows you to execute
packages from the npm registry without installing them in your project dependencies. For example,
you can create a new React app by running the following: npx create-react-app my-app

In Yarn, you can achieve the same result by using the equivalent dlx command: yarn dlx create-
react-app my-app

The rest of the features we’re going to explore are unique to Yarn.

Why Yarn, when we have NPM?

This is the burning question now. NPM works great for thousands of developers but it won’t work
that great for companies like Facebook , Google. If you’ve deleted your node_modules folder for any
reason and run npm install in the project console, npm will re download each and every package
along with their dependencies which is too much time killing. Yarn is great in this purpose. It caches
every package it downloads. If you have ever downloaded the package before, you can install it in
offline mode [Link] also parallelizes operations to maximize resource utilization so install time are
faster than ever, like the rocket trying to escape the earth’s gravity! Yarn is super secured. It uses
checksums to verify the integrity of every installed package before its code is executed. Yarn is
reliable . According to their voice, “ Yarn is able to guarantee that an install that worked on one
system will work exactly the same way on any other system.”

Yarn vs. NPM: How to Choose

Yarn

Advantages

 Supports parallel installation and Zero installs, both of which dramatically increase performance.
 Newer versions of Yarn offer a more secure form of version locking.

 Active user community.

Disadvantages

 Yarn doesn't work with [Link] versions older than version 5.


 Yarn has shown problems when trying to install native modules.

NPM

Advantages

 Easy to use, especially for developers used to the workflow of older versions.
 Local package installation is optimized to save hard drive space.
 The simple UI helps reduce development time.

Disadvantages

 The online NPM registry can become unreliable in case of performance issues. This also means
that NPM requires network access to install packages from the registry.

 Despite a series of improvements across different versions, there are still security vulnerabilities
when installing packages.

Command output can be difficult to read.

Things yarn has that NPM doesn’t

 yarn licenses ls — Allows you to inspect the licenses of your dependencies


 yarn licenses generate-disclaimer — Automatically create your license dependency
disclaimer
 yarn why taco — Identify why ‘taco’ package is installed, detailing which other packages

⬆️Emojis
depend upon it

 Speed 🏃⌁
 Automatic shrinkwrap with the yarn lockfile
 Security-centric design
 yarn upgrade-interactive — Allows you to selectively upgrade specific packages in a simple way

JavaScript Package Manager – Complete Guide to NPM and Yarn

A package manager is a tool developers use to automate finding, downloading, installing,


configuring, upgrading, and removing a system's packages.

Why Do You Need a Package Manager?

Suppose there were no package managers. In that case, you would have to do the following
manually:

 Find all the correct packages for your project


 Verify that the packages don't have any known vulnerabilities
 Download the packages
 Install them at the appropriate location
 Keep track of new updates for all your packages
 Upgrade each package whenever there is a new release
 Remove the packages you no longer need

Manually managing tens or hundreds of packages is a tiresome and time-consuming endeavor.

Therefore, package managers—such as NPM, pNPM, Bower, and Yarn—help automate and eliminate
the tedious process of managing all your packages manually.
Keep in mind that a package manager is not the same as a package registry. So, let's find out the
main difference.

Package Manager vs. Package Registry – What's the Difference?

A package manager is a tool developers use to automatically find, download, install, configure,
upgrade, and uninstall a computer's packages.

NPM (Node Package Manager) and Yarn (Yet Another Resource Negotiator) are two popularly used
package managers.

A package registry is a database (storage) for thousands of packages (libraries, plugins,


frameworks, or tools).

In other words, a package registry is the place packages get published to and installed from.

NPM registry and GitHub Packages are two popularly used package registries.

So, now that we know what a package manager is and why it is needed, we can discuss how to use
the two popular ones—NPM and Yarn.

Note that there are numerous NPM vs. Yarn debates out there – so we will avoid them here because
the best package manager is the one that works best for you.

Therefore, this article will show you how NPM and Yarn work rather than tell you which package
manager is best. It is then up to you to decide which you prefer.

Alternatively, you can choose to use NPM for a specific project and Yarn for another—depending on
which manager you believe is best suited for the job.

So, without any further ado, let's begin by learning how to install the two managers.

How to Install Node Package Manager (NPM)

NPM gets installed automatically while installing Node.

How to Install Yarn

It is best to install Yarn through NPM. So, first, install NPM from the [Link] website.

Once you've installed NPM, proceed to install Yarn like so:

npm install -g yarn

How to Check the Installed Node Version

To check the [Link] version installed on your system, run:

node -v

The -v flag in the snippet above is a shorthand for --version.

How to Check the Installed NPM Version

To check the NPM version installed on your system, run:

npm -v

How to Check the Installed Yarn Version


To check the Yarn version installed on your system, run:

yarn -v

How to Upgrade Node Package Manager

Update to the latest NPM version by running:

npm install npm@latest -g

How to Upgrade NodeJS

Suppose you wish to upgrade your [Link] installation. In that case, you have two options:

Option 1: Upgrade via the NodeJS website

One way to upgrade your NodeJS installation is to manually download and install the latest version
from the [Link] website.

Option 2: Upgrade via a version management tool

Another way to upgrade your NodeJS installation is to use a version manager such as NVM, n,
or nvs.

How to Upgrade Yarn

Update to the latest Yarn version by running:

yarn set version latest

So, now that we have NPM (or Yarn) on our computer, we can start using the installed manager to
find, install, configure, and remove our project's packages.

But what exactly is a package? Let's find out.

What Exactly Is a Package?

A package is a directory (or project) that has a [Link] file used to record information about
it.

Note: You can only publish packages (a project described by a [Link] file) to the NPM
registry.

How to Install Packages

There are two ways to install a package: locally or globally.

Local package installation

A locally installed package is one that you can use only in the project in which you've installed it.

To install a package locally, do the following:

1. Navigate to the root directory of your project from the command line.

2. Install your package using the NPM or Yarn installation command below (depending on the
package manager you've chosen to use for your project).
Note: You must have Node and NPM installed on your system for the NPM (and Yarn) installation
commands below to work. You can get both by installing the latest LTS or the current version from
the [Link] website.

NPM installation command

npm install package-name --save

Note that the --save command above instructs NPM to save package-name in the [Link] file
as one of the packages on which the project depends.

Suppose you wish to install an exact version of a package. In such a case, add a @[version-
number] after the package's name like so:

npm install [email protected] --save

Alternatively, if the package you are installing is for development and testing purposes, use:

npm install package-name --save-dev

The commands above will cause NPM to download three items into your project's root directory:
a node_modules folder, a [Link] file, and a [Link] file. We will discuss these items
in detail later on in this article.

Yarn installation command

yarn add package-name

Suppose you wish to install an exact version of a package. In such a case, add a @[version-
number] after the package's name like so:

yarn add [email protected]

Alternatively, if the package you are installing is for development and testing purposes, use:

yarn add package-name --dev

The commands above will cause Yarn to download three items into your project's root directory:
a node_modules folder, a [Link] file, and a [Link] file. We will discuss these items in detail
later on in this article.

So, now that we know how to install a package locally, we can discuss the global package
installation.

Global package installation

A globally installed package is a package that you can use anywhere on your system.

To install a package globally, run the code below on your terminal:

npm install package-name -g

Alternatively, you can use Yarn like so:

yarn global add package-name

Note that you can run the commands above from any location on your system.

Local vs. global package installation


Generally, it is better to install a package locally. Below are some of the differences between a local
and global installation.

Difference 1: Installation location

A locally installed package gets installed in the directory where you executed the npm install
package-name (or yarn add package-name) command.

Specifically, you will find a project's locally installed packages in its node_module directory.

In contrast, a globally installed package gets installed in a single location on your system. The exact
location depends on your system's configuration.

Difference 2: Package versions

Suppose you installed your package locally. Then, you can use different versions of the same
package for multiple app development.

However, you are forced to use the same package version for all your apps when you install
globally.

Difference 3: Updates

A local installation allows you to choose the project's packages you wish to upgrade to the latest
version. This makes it easier to manage upgrades that break compatibility with other packages.

However, upgrading a globally installed package updates the package for all projects—which can
cause maintenance nightmares if the upgrade breaks compatibility with other packages.

Difference 4: Usage recommendation

Global installation is best for packages you intend to use only on your command line—especially
when they provide executable commands reusable across projects.

However, local installation is best for packages you intend to use in your program—through
the import statement or require() function.

Difference 5: Examples

NPM, React Native CLI, Gatsby CLI, Grunt CLI, and Vue CLI are well-known examples of global
packages.

Common examples of local packages are Webpack, Lodash, Jest, and MomentJS.

Note:

 You can do both local and global installation of packages you intend to use both on the
command line and in your project. Typical examples of such packages
are ExpressJS and CoffeeScript.

 Your package manager does not execute an installed package. NPM (and Yarn) only install
packages to the node_modules directory. And if you had specified the --save command, your
manager would add details about the package to the [Link] file.

 To execute (run) any executable package, you must explicitly do so yourself. We will discuss
how in a later section of this article.
But what exactly are the node_modules folder, [Link] file, [Link] file,
and [Link] file? Let's find out.

What Is a node_modules Folder?

The node_modules directory is the folder where NPM places all the packages it downloads locally
for your project.

What Is a [Link] File?

A [Link] file is a JSON document that package managers—like NPM and Yarn—use to store
information about a specific project.

In other words, a [Link] file is a project's metadata file.

Advantages of a [Link] File

A [Link] file:

 makes it possible to publish your project to the NPM registry


 makes it easy for others to manage and install your package
 helps NPM manage a module's dependencies easily
 makes your package reproducible and shareable with other developers

How to Create a [Link] File

Go to your project's root directory and initialize the creation of a [Link] file by running:

npm init

Or, if your package manager is Yarn, run:

yarn init

Once you've executed the initialization command above, your package manager will walk you
through creating the [Link] file by asking a few questions about your project.

If you wish to skip the questionnaire, you can create a default [Link] file. Let's see how.

How to Create a Default [Link] File

Suppose you prefer to skip the questionnaire prompted by the npm init (or yarn init) command. In
such a case, go to your project's root directory and run:

npm init -y

Or, if your package manager is Yarn, run:

yarn init -y

The command above will use default values extracted from the current directory to create your
project's [Link] file.

Note: The -y flag is a shorthand for --yes.

Once your package manager finishes its initialization process, your project's [Link] file will
contain an object with a set of properties.

Here's an example:
{
"name": "codesweetly-project",
"version": "1.0.0",
"main": "[Link]"
}

You can see that the [Link] file above contains the name, version, and main fields. Let's
learn more about these properties below.

The [Link]'s Fields

The [Link]'s properties make your project usable to package managers and end-users.

Suppose you wish to publish your package to the NPM registry. In that case, your [Link] file
must have the "name" and "version" fields.

However, if you do not intend to publish your package, in that case, all fields—including
the "name" and "version" properties—are optional.

Let's learn more about the commonly used fields in a [Link] file.

name

The "name" field is a property used to record a project's name. The "name" property's value must
be:

 a single word
 lowercase lettering
 and less than or equal to 214 characters

Note that you can join words together with hyphens and underscores.

Here's an example:

{
"name": "code_sweetly-project"
}

version

The "version" field indicates a project's current version number. The "version" property must be in
the form of a [Link] format. It must also follow the semantic versioning guidelines.

Here's an example:

{
"version": "1.0.0"
}

description

The "description" field is a property containing a brief description of a project's purpose. NPM
recommends having a "description" property to make your package easier to find on the NPM
website. Your description will be one of the things that's shown when people run the npm
search command.

Here's an example:
{
"description": "A brief description about this package (project)"
}

main

The "main" field indicates a project's entry point. In other words, when someone runs
the require() function, Node will resolve the invocation to require(<[Link]:main>).

Here's an example:

{
"main": "./src/[Link]"
}

private

The "private" field lets package managers know whether they should publish your project to the
NPM registry.

Here's an example:

{
"private": true
}

If you set your [Link]'s "private" property to true, package managers will not publish your
project.

Therefore, setting the property is an excellent way to prevent accidental publication of your
package.

scripts

The "scripts" field defines the script commands you want to run at various times in your project's
lifecycle.

Here's an example:

{
"scripts": {
"test": "jest",
"dev": "webpack --mode development",
"build": "webpack --mode production",
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
}

The "scripts" field above contains five properties whose values are the commands we want our
package manager to run whenever we invoke the property's key.

So, for instance, running npm run dev will execute the "webpack --mode development" command.

keywords

The "keywords" field specifies an array of keywords that can help people discover your package.
Here's an example:

{
"keywords": [
"drag",
"drop",
"drag and drop",
"dragndrop",
"draggable"
]
}

The "keywords" property is part of the information shown when people run the npm
search command.

author

The "author" field lists a project's author's details.

Here's an example:

{
"author": "Oluwatobi Sofela <oluwatobiss@[Link]>
([Link]
}

You can also write the snippet above as:

{
"author": {
"name": "Oluwatobi Sofela",
"email": "oluwatobiss@[Link]",
"url": "[Link]
}
}

Note that the "email" and "url" properties are optional.

dependencies

The "dependencies" field lists all the packages a project depends on in production.

Here's an example:

{
"dependencies": {
"first-package": "^1.0.4",
"second-package": "~2.1.3"
}
}

So, whenever a user installs your project from the NPM registry, the dependencies property ensures
package managers can automatically find and install the packages listed.

Note that you can add a package to the "dependencies" field through either of the following ways:
 Manually add the name and the semantic version of each package your project depends on in
production.

 Run the npm install package-name --save-prod command on your terminal. Or yarn add
package-name if Yarn is your package manager.

devDependencies

The "devDependencies" field lists all the packages a project does not need in production—but
requires for its local development and testing purposes.

Here's an example:

{
"devDependencies": {
"first-dev-package": "^5.8.1",
"second-dev-package": "3.2.2—4.0.0"
}
}

Note that the packages listed in the "devDependencies" field will be available in the project's
development environment but not on its production server.

Suppose a user installs the project through the npm install (or yarn add) command. In such a case,
the package manager will find and download all the listed devDependencies to the
project's node_modules directory.

Keep in mind that you can add a package to the "devDependencies" field through either of the
following ways:

 Manually add the name and the semantic version of each package on which your project
depends for its development and testing purposes.

 Run the npm install package-name --save-dev command on your terminal. Or yarn add
package-name --dev if Yarn is your package manager.

homepage

The "homepage" field specifies the URL to your project's homepage.

Here's an example:

{
"homepage": "[Link]
}

So, now that we know what a [Link] file is, we can discuss [Link].

What Is a [Link] File?

The [Link] file is a document NPM uses to record the exact version of all the
packages you've installed locally to your project's node_modules directory.

A [Link] file makes an app 100% reproducible in the exact way you published it to the
NPM registry.
So, suppose a user clones your app and runs the npm install command. In such a case, package-
[Link] ensures that the user downloads the exact version of the packages you used to develop
the application.

For instance, let's say a user cloned your app containing no [Link] file, and a
dependency used in the app has a newer version.

Suppose the dependency's version number in the [Link] file has a caret sign (for
example, ^2.6.2). In that case, NPM will install the latest minor version of the dependency—which
might cause the app to produce erroneous results.

However, suppose the user cloned your app containing a [Link] file. In that case, NPM
will install the exact version of the dependency as recorded in the [Link] file—
regardless of whether a newer version exists.

Therefore, users will always get your app the precise way you published it to the NPM registry.

In other words, NPM uses the [Link] file to lock your package's dependencies to the
specific version numbers you used for the project's development.

Note: NPM will update the packages recorded in the [Link] file whenever you run
the npm update command.

What Is a [Link] File?

The [Link] file is a document Yarn uses to record the exact version of all the packages you've
installed locally to your project's node_modules directory.

The [Link] file is comparable to NPM's [Link] lockfile.

We earlier mentioned that your package manager does not execute an installed package—you
must explicitly do so yourself. Let's discuss how.

How to Run an Executable Package

There are several ways to run an executable package. Below are the standard techniques.

Manually locate and execute the package

One way to run an executable package is to type its local path on your command line like so:

./node_modules/.bin/package-name

Add the package to the [Link]'s scripts field

An alternate way to execute a package is to first add it to the "scripts" field of your project's
[Link] file like this:

{
"name": "your_package",
"version": "1.0.0",
"scripts": {
"desired-name": "name-of-package-to-execute"
}
}

Afterward, you can run the package like so:


npm run desired-name

Note that the command above is shorthand for npm run-script desired-name.

Alternatively, you can execute the package with Yarn like so:

yarn run desired-name

Here's an example:

{
"name": "codesweetly-app",
"version": "1.0.0",
"scripts": {
"build": "webpack",
}
}

The snippet above added webpack to your [Link]'s "scripts" field. So, we can now
execute webpack on the command line like this:

npm run build

Or, if your package manager is Yarn, you can run webpack like this:

yarn run build

Use NPX

A faster way to run an executable package is to use NPX like so:

npx package-name

With NPX, you no longer need to add your package to the "scripts" field of your
project's [Link] file.

NPX (Node Package Execute) is a Node package runner that automatically finds and executes a
specified package.

Here's an example:

npx webpack

The command above will automatically find and execute webpack. So, we do not need to add
the "build": "webpack" property to the "scripts" field of our [Link] file.

Note: NPX automatically gets installed when you install Node 8.2/NPM 5.2.0 or higher.

You can also run some code using your preferred [Link] version. Let's find out how.

How to Run Code Using Your Preferred [Link] Version

You can use the @ character and the node npm package to specify the [Link] version you wish to
use to execute your code.

Here's an example:

npx node@7 [Link]


The snippet above tells NPX to run [Link] with the latest version of Node from version 7 major.

Using the node@ command is a helpful way to avoid using [Link] version management tools
like nvm to switch between Node versions.

Suppose you wish to confirm the Node version NPX will use to run your code. In that case, run:

npx node@7 -v

The snippet above will display the latest Node version from version 7 major that NPX will use to run
your code—for example, v7.10.1.

How to Check for Outdated Local Packages

To determine if any of your project's packages are outdated, run:

npm outdated

If the command outputs nothing, it means all your project's packages are up to date.

Otherwise, see this npm-outdated article for a detailed explanation of the command's output.

Alternatively, you can use Yarn like so:

yarn outdated

Note: To check a specific package's outdated status, add the package's name after
the outdated keyword—for example, npm outdated lodash.

How to Check for Outdated Global Packages

To confirm which global package is outdated, run:

npm outdated -g --depth=0

How to Check for Locally Installed Packages

Here are three ways to check for locally installed packages:

Locally installed packages and their dependencies

npm list

Or use Yarn like so:

yarn list

Locally installed packages—without their dependencies

npm list --depth=0

Or,

yarn list --depth=0

Check if a specific package got installed locally

npm list package-name


How to Check for Globally Installed Packages

Here are three ways to check for globally installed packages:

Globally installed packages and their dependencies

npm list -g

Or use Yarn like so:

yarn list -g

Globally installed packages—without their dependencies

npm list -g --depth=0

Or,

yarn list -g --depth=0

Check if a specific package got installed globally

npm list -g package-name

How to Update Packages

Here's how to update packages with NPM and Yarn:

How to update a specific package to its latest version

npm update package-name

Or, for projects managed with Yarn, run:

yarn upgrade package-name

How to update all of a project's locally installed packages

npm update

Or,

yarn upgrade

How to update a specific globally installed package

You can update a globally installed package like this:

npm update package-name -g

How to update all your system's globally installed packages

npm update -g

How to Uninstall Packages

Here's how to uninstall packages with NPM and Yarn:

How to uninstall a package from a specific project


First, navigate to the project's root directory from the command line and run:

npm uninstall package-name

Note:

 Add the -S (or --save) flag to remove references to the package in the dependencies field of the
project's [Link] file.

 Add the -D (or --save-dev) flag to remove references to the package in


the devDependencies field of the project's [Link] file.

For projects managed with Yarn, run:

yarn remove package-name

Note: The yarn remove command will automatically update the


project's [Link] and [Link] files.

How to uninstall a global package

npm uninstall package-name -g

Note that it is best practice not to remove packages manually from the node_modules folder as
such action can affect other modules depending on it.

But what exactly is a module in NodeJS? Let's find out below.

What Exactly Is a Module in NodeJS?

A module in NodeJS is any file in the node_modules folder that the computer can load through
Node's require() function.

Here's an example:

const myModule = require("./[Link]");

Suppose the computer successfully used the require() function to load the [Link] file. In
such a case, it means [Link] is a module—assigned to the myModule variable.

Keep in mind that a module may also be a package—but not always.

A module is not a package if it does not have a [Link] file used to record information about
it.

Also, note that for a module to be loadable by the require() function, the module must be one of the
following:

 A package—whose [Link] file contains a "main" field.

 A JavaScript file.

How to Publish Your Project to the NPM Registry

NPM is a free registry for public package authors.

So, you can use it to publish any project (folder) from your computer that has a [Link] file.

Below are the steps required to share your package with the world.
Step 1: Sign in or sign up

Go to the NPM website and sign in (or sign up if you do not yet have an account).

Note: make sure that you verify your email after creating a new account. Otherwise, you will get
a 403 Forbidden error while publishing your package.

Step 2: Log in

Login to your NPM account from the command line like so:

npm login

Note: You can use the npm whoami command to check if you are currently logged in.

Step 3: Publish your package!

Go to your project's root directory and publish it like so:

npm publish

Make sure that your package's name does not currently exist on NPM. Otherwise, you will get an
error while publishing.

You can use the npm search command (or the NPM website's search bar) to search if the name you
wish to use already exists on NPM.

Suppose all the suitable names for your package are already taken. In that case, NPM allows you to
publish your project as a scope.

In other words, you can publish your package as a sub-section of your username. Let's see how
below.

How to publish your package as a scope of your username

Open your [Link] file and prefix your package's name with your username.

Here's an example:

{
"name": "@username/package-name",
"version": "1.0.0",
"main": "[Link]",
"license": "MIT"
}

NPM's default setting assumes that a scoped name package is a private project. So, you will get an
error if you use the npm publish command to share a scoped name package.

Therefore, to publish your package as a scope of your username, add the --access=public flag to
the npm publish command:

npm publish --access=public

Note: You can make your project a scoped package during the initialization process by using
the npm init --scope=username command instead of npm init.

You might also like