$ node -v
v4.2.2
$ npm -v
2.14.7
Your version numbers may vary as Node and npm are updated. Broadly speaking,
npm manages installed packages. A package can be anything from a full application,
to sample code, to a module or library that you’ll use in your project.
npm supports installing packages at two levels: globally and locally. Global packages
are usually command-line tools that you’ll use in the development process. Local
packages are project-specific. Installing a package is done with the
npm install
com‐
mand. Let’s install the popular Underscore package to see how it works. In your
project root, run the following:
$ npm install underscore
[email protected] node_modules\underscore
npm is telling you that it installed the latest version of Underscore (1.8.3 as I write
this; yours will probably be different). Underscore is a module with no dependencies,
so the output from npm is very brief; for some complex modules, you may see pages
of text go by! If we wanted to install a specific version of Underscore, we can specify
the version number explicitly:
$ npm install [email protected]
[email protected] node_modules\underscore
So where did this module actually get installed? If you look in your directory, you’ll
see a new subdirectory called node_modules; any local modules you install will go in
this directory. Go ahead and delete the node_modules directory; we’ll be re-creating it
in a moment.
As you install modules, you’ll want to keep track of them somehow; the modules you
install (and use) are called dependencies of your project. As your project matures,
you’ll want a concise way to know what packages your project depends on, and npm
does this with a file called package.json. You don’t have to create this file yourself: you
can run
npm init
, and interactively answer some questions (you can simply press
Enter for each question and accept the defaults; you can always edit the file and
change your answers later). Go ahead and do this now, and take a look at the gener‐
ated package.json file.
Dependencies are split into regular dependencies and dev dependencies. Dev depen‐
dencies are packages that your app can run without, but are helpful or necessary in
building your project (we’ll see examples of these soon). From here on out, when you
install local packages, you should add either the
--save
or
--saveDev
flag; if you
don’t, the package will be installed, but not listed in the package.json file. Let’s go
ahead and reinstall Underscore with the
--save
flag:
22 | Chapter 2: JavaScript Development Tools