Package Management

Tutorial 4 of 4

Introduction

In this tutorial, we'll be exploring package management in JavaScript with npm (Node Package Manager). npm is a default package manager for the JavaScript runtime environment Node.js. It consists of a command-line client, also called npm, and an online database of public and paid-for private packages, called the npm registry.

What the user will learn:
- What is npm
- How to install npm
- How to create a new project with npm
- How to install packages with npm
- How to update and remove packages

Prerequisites:
- Basic knowledge of JavaScript
- Node.js installed on your machine

Step-by-Step Guide

npm Installation

If you've installed Node.js, you already have npm! You can check if it's installed by running node -v and npm -v in your terminal or command prompt. It will display the version of Node and npm installed.

Initializing a New Project with npm

To start a new project, navigate to your project folder in the terminal and type npm init. This will start a series of prompts to create a package.json file, which will hold metadata about your project and the packages it depends on.

$ npm init

Installing Packages with npm

To install a package, you use the npm install command, followed by the package name.

$ npm install <package-name>

This will download the package and its dependencies and save them into a folder named node_modules. It will also add the package to your package.json file.

Updating and Removing Packages

You can update packages with npm update and remove them with npm uninstall.

$ npm update <package-name>
$ npm uninstall <package-name>

Code Examples

Example 1: Installing a package

Let's install the package lodash, a popular utility library in JavaScript.

$ npm install lodash

Example 2: Using a package

Now, let's use lodash in a JavaScript file. Create a index.js file and add the following code:

// Import lodash
const _ = require('lodash');

// Use lodash to manipulate an array
const array = [1, 2, 3, 4, 5];
const reversed = _.reverse(array);

console.log(reversed); // Output: [5, 4, 3, 2, 1]

Summary

In this tutorial, we've learned about npm and how to manage packages with it. We've seen how to start a new project, install, update and remove packages.

The next step would be exploring more npm commands and learning about package-lock.json, a file automatically created after an npm installation.

Practice Exercises

Exercise 1:
Initialize a new npm project and install the express package. Create an app.js file, import express and start a server on port 3000.

Exercise 2:
Install the moment package and use it in a JavaScript file to display the current date and time in a formatted manner.

Exercise 3:
Update the express package to its latest version, then remove the moment package.

Solutions and explanations will be provided upon request. You can also refer to the npm documentation for more practice and information.