Solve - Cannot find module 'lodash' error

avatar

Borislav Hadzhiev

Sun Mar 27 20222 min read

banner

Photo by Anna Dudkova

Solve - Cannot find module 'lodash' error #

To solve the error "Cannot find module 'lodash'", make sure to install the lodash package by opening your terminal in your project's root directory and running the following command: npm i lodash. If you use TypeScript, install the typings by running npm i -D @types/lodash.

Open your terminal in your project's root directory (where your package.json file is located) and run the following commands:

shell
npm install lodash # 👇️ only if you use TypeScript npm install --save-dev @types/lodash

This will add the lodash package to the dependencies of your project.

Now you should be able to import and use the package like so:

index.js
import _ from 'lodash'; console.log(_.add(100, 200)); // 👉️ 300

If you use TypeScript and get the "Cannot find module 'lodash' or its corresponding type declarations" error, open your tsconfig.json file and make sure the types array contains the string node.

tsconfig.json
{ "compilerOptions": { "types": [ "node" ] }, }
This should fix the error and now TypeScript should be able to find the type definitions for the lodash module.

If the "Cannot find module 'lodash'" error is not resolved, try to delete your node_modules and package-lock.json (not package.json) files, re-run npm install and restart your IDE.

shell
# 👇️ delete node_modules and package-lock.json rm -rf node_modules rm -f package-lock.json # 👇️ clean npm cache npm cache clean --force npm install
Make sure to restart your IDE and dev server if the error still persists. VSCode often glitches and a reboot solves things sometimes.

If you're still getting the "Cannot find module 'lodash'" error, open your package.json file and make sure it contains the lodash package in the dependencies object.

package.json
{ // ... rest "dependencies": { "lodash": "^4.17.21", }, "devDependencies": { // 👇️ only if you use TypeScript "@types/lodash": "^4.14.180", } }

You can try to manually add the line and re-run npm install.

shell
npm install

Or install the latest version of the package:

shell
npm install lodash@latest # 👇️ only if you use TypeScript npm install --save-dev @types/lodash@latest
Use the search field on my Home Page to filter through my more than 1,000 articles.