+ - 0:00:00
Notes for current slide
Notes for next slide

npm

Learn how to use npm, the most popular Node.js package manager, and the largest code registry in the world with over a quarter million packages.

You will need

  • A Unix CLI

Recommended reading

1 / 44

What is npm?

npm

"npm is the package manager for JavaScript. Find, share, and reuse packages of code from hundreds of thousands of developers — and assemble them in powerful new ways."

2 / 44

Why use a package manager?

npm > What is npm?

  • Use code or applications that other developers have written to solve particular problems
  • Regularly check if there are any upgrades and download them
  • Share your own code with the community or reuse code across projects

3 / 44

There are many package managers

npm > What is npm?

For programming languages:

Package manager Language
Composer PHP
Maven Java
npm Node.js
RubyGems Ruby
pip Python

For operating systems:

Package manager OS
Advanced Package Tool (apt) Debian, Ubuntu
Homebrew (brew) Mac OS X
Yellowdog Updater, Modified (yum) RHEL, Fedora, CentOS
4 / 44

The npm registry

npm > What is npm?

The npm registry hosts over a million packages of reusable code — the largest code registry in the world.

It contains more than double the next most populated package registry (the Apache Maven repository).

5 / 44

npm packages

npm > What is npm?

An npm package or module is basically a reusable piece of code that you can install and use. It's composed of:

  • A directory with some files in it (what will be installed)
  • A package.json file with some metadata about the package:
{
"name": "my-project",
"version": "1.3.2",
"description": "It's great",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.13.3",
"lodash": "~3.1.0"
},
"keywords": [ "awesome", "project" ],
"author": "John Doe <john.doe@example.com>",
"license": "MIT"
}
6 / 44

The npm command

npm

npm is also a set of command line tools that work together with the registry.

7 / 44

How do I use it?

npm > The npm command

$> npm help
Usage: npm <command>
where <command> is one of:
access, adduser, bin, bugs, c, cache, completion, config,
ddp, dedupe, deprecate, dist-tag, docs, edit, explore, get,
help, help-search, i, init, install, install-test, it, link,
list, ln, login, logout, ls, outdated, owner, pack, ping,
prefix, prune, publish, rb, rebuild, repo, restart, root,
run, run-script, s, se, search, set, shrinkwrap, star,
stars, start, stop, t, tag, team, test, tst, un, uninstall,
unpublish, unstar, up, update, v, version, view, whoami
npm <cmd> -h quick help on <cmd>
npm -l display full usage info
npm help <term> search for help on <term>
npm help npm involved overview
8 / 44

npm init

npm

Create a new package

9 / 44

Interactively create a package.json file

npm > npm init

Create and move into a new project directory:

$> cd /path/to/projects
$> mkdir npm-demo
$> cd npm-demo

Run npm init:

$> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
...
Press ^C at any time to quit.
name: (npm-demo)
version: (1.0.0)
description: npm demo
entry point: (index.js)
test command:
git repository:
keywords: npm, demo
author: John Doe <john.doe@example.com>
license: (ISC)
10 / 44

What it looks like

npm > npm init

{
"name": "npm-demo",
"version": "1.0.0",
"description": "npm demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [ "npm", "demo" ],
"author": "John Doe <john.doe@example.com>",
"license": "ISC"
}

Read the documentation to find out everything you can configure in this file.

11 / 44

npm install

npm

Install a package

12 / 44

Installing packages

npm > npm install

When you install a package with the npm install command, npm creates a node_modules directory in the current working directory. It then saves the downloaded packages in that directory:

$> npm install lodash
npm-demo@1.0.0 /path/to/projects/npm-demo
└── lodash@4.17.4
$> ls
node_modules package.json package-lock.json
$> ls node_modules
lodash

13 / 44

Using installed packages

npm > npm install

Any script that is in the same directory as package.json and node_modules can import the installed packages:

Create a script.mjs file in the project and run it::

import _ from 'lodash';
let numbers = [ 1, 1, 2, 3, 2 ];
console.log(_.uniq(numbers));
$> node script.mjs
[ 1, 2, 3 ]

You have used the uniq function from the lodash package, which returns an array with its duplicate elements removed.

14 / 44

Importing ECMAScript Modules

npm > npm install

As was mentionned during the presentation on Node, we will be using ECMAScript modules during this course.

In your package.json, add the following property:

type: "module"

This will allow you to use ECMAScript modules without having to name your files with the .mjs extension. You can now rename it to .js.

$> mv script.mjs script.js
$> node script.js
[ 1, 2, 3 ]
15 / 44

Tracking installed packages

npm > npm install

Now remove the node_modules directory:

rm -fr node_modules

Your script should no longer work since the lodash package is no longer available:

$> node script.js
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'lodash'
Error: Cannot find module 'lodash'

Deleting the node_modules directory is not a common real-world scenario, However, it can get quite large, so most people have it in their .gitignore file in their Git repositories, since you just have to run npm install to get your dependencies back.

That means that when cloning your project, your colleagues won't get the node_modules directory.

16 / 44

Re-installing dependencies manually

npm > npm install > Tracking installed packages

You could reinstall all these packages manually, but imagine that you have dozens of dependencies. Do you want each team member to re-type the same npm install commands all the time?

This is the typical list of dependencies for a barebones Express web application:

17 / 44

npm saves the dependencies to package.json

npm > npm install

npm automatically tracks the dependencies you install. There is a --save option that was required for that in earlier versions, but it's the default now.

When you ran npm install, a new dependencies section should have appeared in your package.json file:

18 / 44

npm install with a package.json

npm > npm install

Delete the node_modules directory again and simply run npm install with no other arguments:

$> rm -fr node_modules
$> npm install
npm-demo@1.0.0 /path/to/projects/npm-demo
└── lodash@4.17.4

npm has installed the lodash package again. If you don't specify a package to install, the install command will read the package.json and install the dependencies listed there.

The package-lock.json also contains the precise versions of the packages you installed. That way, your entire team can reproduce the exact same package structure as on your machine.

19 / 44

The --save-dev option

npm > npm install

You often use two kinds of packages:

  • Production dependencies that your program or application needs to run (e.g. a database client)
  • Development dependencies that you use during development but do not need to run the application (e.g. a live-reload server)

Use the --save-dev option to save your development dependencies:

$> npm install --save-dev gulp

A devDependencies section will be added to your package.json:

20 / 44

The --production option

npm > npm install

Use npm install with no arguments when you want to install all dependencies, including development dependencies:

$> npm install

Use the --omit=dev flag to install only production dependencies (e.g. on a server, where you will only need to run your program and will not need your development tools):

$> npm install --omit=dev

21 / 44

The --global option

npm > npm install

Some packages can be installed globally. Use the --global or -g option:

$> npm install --global http-server

If you get an EACCES error, execute the following commands:

$> mkdir ~/.npm-global
$> npm config set prefix '~/.npm-global'
$> echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bash_profile
$> echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.zshrc

Re-open your CLI, then retry the installation, which should work this time:

$> npm install --global http-server
22 / 44

Global packages

npm > npm install > The --global option

Global packages are NOT installed in the current directory. They are installed in a system directory and are global to your machine (you don't need to re-install them for each project).

Global packages provide new commands that you can use in your CLI. In this case, the http-server package is a simple command-line HTTP server:

$> http-server
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
http://10.178.123.132:8080
Hit CTRL-C to stop the server
23 / 44

Where are global packages installed?

npm > npm install > The --global option

Use npm config to find out where global packages are installed on your machine:

$> npm config get prefix
/usr/local
$> ls /usr/local/lib/node_modules
http-server

You cannot use --save with global packages. You do not need to since they are global to your machine and available anywhere in the CLI. However, if you reset your machine or Node.js installation, you will have to reinstall manually.

24 / 44

Common mistakes

npm

It happens.

25 / 44

Missing package.json file

npm > Common mistakes

If you forgot to add a package.json file to your project, npm will still install your dependencies and log a warning that is easy to miss:

$> npm install --save lodash
npm WARN saveError ENOENT: no such file or directory,
open '/path/to/projects/npm-demo/package.json'
/path/to/projects/npm-demo
└── lodash@4.17.4

26 / 44

Wrong directory

npm > Common mistakes

Npm will not know if you are in the wrong directory. It will simply install packages there. Of course, you will NOT be able to import them from your project:

27 / 44

The behavior of import

npm

28 / 44

Requiring your own modules

npm > The behavior of import

You can import your own Node.js scripts with relative file paths:

Beware of circular dependencies. In this example, you should do one or the other, not both.

29 / 44

Requiring packages installed with npm

npm > The behavior of import

You can import packages you installed with npm using their name:

30 / 44

Global packages installed with npm

npm > The behavior of import > Requiring packages installed with npm

You CANNOT import packages you installed globally with npm. They provide new commands but cannot be used in code:

31 / 44

Importing core Node.js modules

npm > The behavior of import

When you give a name to import, it will also look for a core Node.js modules with that name:

32 / 44

Import summary

npm > The behavior of import

Statement What is imported
import * as script from './script' The script.js file in the current directory (relative to the file using import)
import * as script from './dir/script' The script.js file in the dir directory (relative to the file using import)
import * as script from '../script' The script.js file in the parent directory (relative to the file using import)
import myModule from 'my-module' The my-module npm package (if found in node_modules in the same directory or any parent directory)
OR
The core Node.js module with that name (if there is one)
33 / 44

More complex packages

npm

The npm registry has many packages, some small, some big. Let's install Express, a web application framework:

$> npm install express

Create a server.js file with the following content:

import express from 'express';
const app = express();
app.get('/', function(req, res) {
res.send('Hello ' + req.query.name + '!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
34 / 44

Run a web app

npm > More complex packages

Run the file:

$> node server.js
Example app listening on port 3000!

Visit http://localhost:3000?name=World in your browser.

You have a running web application server!

35 / 44

npm scripts

npm

npm is not only a package installer, it's also a package manager

36 / 44

Lifecycle scripts

npm > npm scripts

For programs that can be long-lived, such as web servers, npm defines standard lifecycle scripts that you should use to control your program. Here are a few:

Command Purpose
npm start Run your program
npm stop Stop your program
npm restart Restart your program
npm test Run automated tests for your program

Read the documentation to learn about all the available lifecycle scripts.

37 / 44

The scripts property

npm > npm scripts

In order for your program to respond to these npm start|stop|... commands, the corresponding scripts should be defined in your package.json file under the scripts property:

Here we define that running npm start should execute the server.js file with Node.js:

$> npm start
> npm-demo@1.0.0 start /path/to/projects/npm-demo
> node server.js
Example app listening on port 3000!
38 / 44

Custom scripts

npm > npm scripts

You can also define your own custom scripts:

{
"name": "npm-demo",
"scripts": {
"hello": "echo Hello World"
},
...
}

These scripts are run with npm run <script>:

$> npm run hello
> npm-demo@1.0.0 serve-static /path/to/projects/npm-demo
> echo Hello World
Hello World
39 / 44

npm publish

npm

Publish a package

40 / 44

What do I need to publish?

npm > npm publish

You need a valid package.json file.

You should also set the main property:

{
"name": "npm-demo",
"main": "./script.js",
...
}

When people import your module after installing it, they will get the same result as if they had imported that file.

41 / 44

Publishing

npm > npm publish

Publishing is as simple as running the npm publish command in the directory where your package.json file is located:

npm publish

You of course need an npm account.

You can only publish a new package if the package name is not already used. Names are registered on a first-come, first-serve basis.

42 / 44

Avoiding publication

npm > npm publish

Sometimes you write code that should not be published:

  • A website (something that makes no sense to import)
  • A private package with confidential information

In these cases, you can set the private property of the package.json file:

{
"name": "npm-demo",
"private": true,
...
}

npm publish will then refuse to publish the package.

43 / 44

Resources

npm

Documentation

44 / 44

What is npm?

npm

"npm is the package manager for JavaScript. Find, share, and reuse packages of code from hundreds of thousands of developers — and assemble them in powerful new ways."

2 / 44
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
t Restart the presentation timer
?, h Toggle this help
Esc Back to slideshow