Package Manager: Laying Out The Basics
Package Manager: 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.
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.
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.
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
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:
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:
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.
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.
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!
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).
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.
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:
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.
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.
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:
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
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:
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>
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
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
To install a package globally on your system, you use the following command: npm install
<package_name> --global
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.
npm --version
Yarn can be installed through the command line of your terminal. I like to use the integrated
terminal of VSCode for this.
yarn --version
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.
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.
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.
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.
yarn why
yarn licenses ls.
You will notice very soon, that node_modules is a very heavy folder. This is completely normal.
yarn outdated
npm outdated
$ 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
yarn upgrade
npm update
npm and Yarn share many commands, but there are also many non-identical commands. Let’s first
explore some of the identical commands:
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:
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:
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.
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.
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.
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.
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
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.
Disadvantages
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.
⬆️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
Suppose there were no package managers. In that case, you would have to do the following
manually:
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.
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.
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.
It is best to install Yarn through NPM. So, first, install NPM from the [Link] website.
node -v
npm -v
yarn -v
Suppose you wish to upgrade your [Link] installation. In that case, you have two options:
One way to upgrade your NodeJS installation is to manually download and install the latest version
from the [Link] website.
Another way to upgrade your NodeJS installation is to use a version manager such as NVM, n,
or nvs.
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.
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.
A locally installed package is one that you can use only in the project in which you've installed it.
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.
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:
Alternatively, if the package you are installing is for development and testing purposes, use:
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.
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:
Alternatively, if the package you are installing is for development and testing purposes, use:
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.
A globally installed package is a package that you can use anywhere on your system.
Note that you can run the commands above from any location on your system.
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.
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.
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.
The node_modules directory is the folder where NPM places all the packages it downloads locally
for your project.
A [Link] file is a JSON document that package managers—like NPM and Yarn—use to store
information about a specific project.
A [Link] file:
Go to your project's root directory and initialize the creation of a [Link] file by running:
npm init
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.
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
yarn init -y
The command above will use default values extracted from the current directory to create your
project's [Link] file.
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 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
Here's an example:
{
"author": "Oluwatobi Sofela <oluwatobiss@[Link]>
([Link]
}
{
"author": {
"name": "Oluwatobi Sofela",
"email": "oluwatobiss@[Link]",
"url": "[Link]
}
}
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
Here's an example:
{
"homepage": "[Link]
}
So, now that we know what a [Link] file is, we can discuss [Link].
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.
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.
We earlier mentioned that your package manager does not execute an installed package—you
must explicitly do so yourself. Let's discuss how.
There are several ways to run an executable package. Below are the standard techniques.
One way to run an executable package is to type its local path on your command line like so:
./node_modules/.bin/package-name
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"
}
}
Note that the command above is shorthand for npm run-script desired-name.
Alternatively, you can execute the package with Yarn like so:
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:
Or, if your package manager is Yarn, you can run webpack like this:
Use NPX
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.
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:
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.
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.
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.
npm list
yarn list
Or,
npm list -g
yarn list -g
Or,
npm update
Or,
yarn upgrade
npm update -g
Note:
Add the -S (or --save) flag to remove references to the package in the dependencies field of the
project's [Link] file.
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.
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:
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.
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 JavaScript file.
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.
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.
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:
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.