Installing Packages
Now that you know what npm is, it's time to actually install packages! This is the most common npm task you'll do. Whether you need a library for dates, HTTP requests, or utility functions, installing packages is simple.
Installing Packages – The Basics
The basic command to install a package is:
npm install You can also use the shorthand:
npm i Think of `npm install` as ordering from a catalog. You specify what you want, and npm downloads it and puts it in your project's `node_modules` folder.
Example: Installing a Popular Package
Let's install `lodash`, a popular utility library:
npm install lodashAfter running this, you'll notice:
- A `node_modules` folder appears (if it didn't exist).
- A `package-lock.json` file is created or updated.
- In `package.json`, you'll see a new `dependencies` section with `"lodash": "^4.17.21"` (or similar).
Using an Installed Package
Once installed, you can use the package in your code with `require()`:
const _ = require('lodash');
const numbers = [1, 2, 3, 4, 5];const shuffled = _.shuffle(numbers);console.log(shuffled);Global vs Local Packages
By default, `npm install` installs packages **locally** – they are only available in that project (inside `node_modules`).
Sometimes you want to install a package **globally** so you can use it as a command-line tool anywhere on your system. For example, `nodemon` (auto-restarts Node apps) or `create-react-app`.
To install globally, add the `-g` flag:
npm install -g nodemonNow you can run `nodemon` from any terminal.
Development Dependencies
Some packages are only needed during development (testing, building, linting). You can save them as `devDependencies` using the `--save-dev` flag:
npm install --save-dev jestIn `package.json`, this will appear under `devDependencies` instead of `dependencies`. When you deploy your app to production, you can run `npm install --production` to skip installing dev dependencies.
Installing Multiple Packages
You can install several packages at once:
npm install express lodash momentInstalling Specific Versions
By default, npm installs the latest version. But you can specify a version:
npm install express@4.17.1Uninstalling Packages
To remove a package:
npm uninstall lodashThis removes it from `node_modules` and updates `package.json`.
Listing Installed Packages
To see what packages are installed locally:
npm listFor a more concise view (only top-level packages):
npm list --depth=0Two Minute Drill
- `npm install
` installs a package locally. - `-g` flag installs globally (for command-line tools).
- `--save-dev` saves as a development dependency.
- Installed packages go into `node_modules` and are listed in `package.json`.
- Use `npm uninstall` to remove packages.
- Use `npm list` to see what's installed.
Need more clarification?
Drop us an email at career@quipoinfotech.com
