How to Install Lodash with NPM

This guide provides a straightforward walkthrough on how to install the Lodash JavaScript utility library using npm. You will learn the exact terminal commands required to add Lodash to your project dependencies, how to install TypeScript definitions if needed, and the most efficient methods for importing Lodash functions into your codebase.

Step 1: Initialize Your Project

Before installing any npm packages, ensure you have a package.json file in your project's root directory. If you do not have one already, open your terminal and run:

npm init -y

Step 2: Install Lodash

To install Lodash as a production dependency, run the following command in your terminal:

npm install lodash

This command downloads the latest stable version of Lodash into your node_modules folder and adds "lodash" to the dependencies section of your package.json.

Step 3: Install TypeScript Types (Optional)

Lodash is written in JavaScript. If you are developing a project with TypeScript, you should also install the community-maintained type definitions as a development dependency:

npm install --save-dev @types/lodash

Step 4: Import and Use Lodash

Once installed, you can import Lodash into your JavaScript or TypeScript files.

CommonJS (Node.js default)

// Import the entire library
const _ = require('lodash');

// Use a Lodash method
const numbers = [1, 2, 3, 4];
console.log(_.chunk(numbers, 2)); // Output: [[1, 2], [3, 4]]

ES6 Modules (Modern JavaScript / Bundlers)

// Import the entire library
import _ from 'lodash';

// Or import only specific methods to optimize bundle size
import chunk from 'lodash/chunk';

const numbers = [1, 2, 3, 4];
console.log(chunk(numbers, 2)); // Output: [[1, 2], [3, 4]]

Importing specific methods directly from lodash/<method> is recommended for frontend applications, as it allows module bundlers like Webpack, Rollup, or Vite to perform tree-shaking and keep your final build size minimal.