NPM

Managing Dependencies Efficiently

Node Package Manager

NPM is the package manager that Node comes bundled with. We use this piece of software to install dependencies in our code. This saves us the trouble of having to find and manually download and install packages that we want to use in our code.


Usage

Once you install Node, you also install NPM by default. You can use NPM from your terminal. Let's walk through it's usage with an example project. Open Git Bash and let's make a new project.

  1. Navigate to ~/wcci/code.
  2. Make a new directory: mkdir hello-npm && cd hello-npm
  3. Initialize a new Node project: npm init -y
  4. Open in VSCode: code ..

Once you do this you will have a new file in your directory. Let's explore it.


package.json

package.json is essentially a configuration file for NPM. It allows you to manage dependencies and details of your project as well as declare scripts that can be run in your terminal.

{
  "name": "hello-npm",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Don Hamilton III <donhamiltoniii@gmail.com> (https://donhamiltoniii.com)",
  "license": "ISC"
}

Adding Dependencies

We can add dependencies using NPM. In fact, this is the bulk of what we use NPM for. Let's add Parcel to this project so we can write modular code.

$ npm i parcel-bundler

Once that installs, we will have a new directory called node_modules. This is where we store dependencies and where node will look for them when we reference them in our code.


Referencing Dependencies

To see how we reference dependencies in our code, let's add one more:

$ npm i lodash

Once this downloads, make a file called index.js in the project root and add the following code.

import _ from "lodash";

_.forEach(["Hello", "NPM!"], val => console.log(val));

Node will now look for that dependency in node_modules when you run the program


Conclusion

NPM is a tremendously important tool. It saves us so much time and effort by organizing and building our projects for us. Check out the documentation to familiarize yourself further.