Step 1: Adding Express as a Dependency

Create a new folder. I will call mine express-app. Open this folder in the terminal and run the following command:

npm init -y

The command will create a package.json file inside the express-app folder:

{
  "name": "express-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

By convention, every Node application (package) has a package.json file at its root folder. The file holds metadata relevant to the project. It is also used, by NPM, for managing the project's dependencies, scripts, version and a whole lot more. We will explore this further in future.

A Node package a folder containing a program described by a package.json file.

Next, run the following command in the terminal:

npm install express

The npm install command installs a package, and any packages that it depends on.

After installing Express, it can be used in our Node application. This means we can, for instance, create a file index.js, and import Express as a module:

// index.js file
const express = require("express");

// use express in your application!

Notice three changes as a result of installing Express:

  1. The following property was added to package.json

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

    This simply states that the Express package version 4.17.1 or higher is a "dependency" of our application.

  2. A folder node_modules was added to express-app. This folder has a lot of content in it! Essentially, the Express package itself is built out of several other packages which themselves are made of other packages. All of these packages are "installed" (downloaded to node_modules folder) so that Express (and thus your app) can work as expected.

    Make sure to always exclude node_modules folder from your Git repository. Add node_modules/* to your .gitignore file.

  3. A file, package-lock.json is added to the root of your project. As stated earlier, the Express framework itself has many other dependencies. All the packages needed to make Express work are also added as a dependency of your project with their exact versions to the package-lock.json file.

    The package-lock.json is automatically generated and modified. You should never directly edit it.

    Make sure to include package-lock.json in your Git repository. For any subsequent installs of your project, you need this file to get the exact dependencies which your project is build on.