Today I tried to learn more about Google Web Starter Kit so I followed these instructions and after a lot of fight and problem I just tried to start a local server (the first task we’ll look at is: $ gulp serve
.) and received this error:
C:gwsk>gulp serve
Error: Cannot find module 'lodash'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:gwsknode_modulesbrowser-syncnode_modulesportsc
anner-pluslibindex.js:3:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:gwsknode_modulesbrowser-synclibutils.js:6:19)
Honestly I’m completely lost here, so any help is pretty welcome. I’m new to node.js, to gulp, I just wanted it to try GWSK but turn into a headache :(… I’m a web designer not developer….
Oleg
9,2712 gold badges44 silver badges58 bronze badges
asked Dec 11, 2014 at 19:48
1
Be sure to install lodash in the required folder. This is probably your C:gwsk directory.
If that folder has a package.json file, it is also best to add —save behind the install command.
$ npm install lodash --save
The package.json file holds information about the project, but to keep it simple, it holds your project dependencies.
The save command will add the installed module to the project dependencies.
If the package.json file exists, and if it contains the lodash dependency you could try to remove the node_modules folder and run following command:
$ npm cache clean
$ npm install
The first command will clean the npm cache. (just to be sure)
The second command will install all (missing) dependencies of the project.
user
4,8555 gold badges17 silver badges35 bronze badges
answered Feb 12, 2015 at 14:37
bohem.bebohem.be
1,7331 gold badge14 silver badges17 bronze badges
3
I found deleting the contents of node_modules and performing npm install
again worked for me.
answered Apr 14, 2016 at 9:04
Jay Byford-RewJay Byford-Rew
5,5661 gold badge34 silver badges36 bronze badges
1
Maybe loadash needs to be installed. Usually these things are handled by the package manager. On your command line:
npm install lodash
or maybe it needs to be globally installed
npm install -g lodash
answered Dec 11, 2014 at 19:56
Will ShaverWill Shaver
12.1k5 gold badges49 silver badges64 bronze badges
1
Reinstall ‘browser-sync’ :
rm -rf node_modules/browser-sync
npm install browser-sync --save
answered Aug 21, 2015 at 6:13
SaebyeokSaebyeok
941 silver badge3 bronze badges
1
If there is a package.json
, and in it there is lodash
configuration in it. then you should:
npm install
if in the package.json
there is no lodash
:
npm install --save-dev
answered Feb 26, 2018 at 3:48
aircraftaircraft
23.1k24 gold badges87 silver badges161 bronze badges
though npm install lodash
would work, I think that it’s a quick solution but there is a possibility that there are other modules not correctly installed in browser-sync
.
lodash is part of browser-sync
. The best solution is the one provided by Saebyeok. Re-install browser-sync
and that should fix the problem.
answered Dec 13, 2015 at 16:14
For me, I update node and npm to the latest version and it works.
answered Jun 22, 2019 at 1:29
G.yxG.yx
6232 gold badges6 silver badges15 bronze badges
The above error run the commend line
please change the command
$ node server
it’s working and server is started
answered Nov 11, 2016 at 6:57
To fix the error “Cannot find module ‘lodash’” in Javascript, you must have npm and lodash knowledge. So before we get into the main content, let’s find out what they are.
What is npm, and what is lodash?
NPM stands for Node Package Manager, a tool to create and manage javascript libraries for Nodejs. If you work with javascript regularly, you must have heard about it.
Lodash, like all other packages, is hosted on npm. Lodash’s predecessor is underscored – a well-known javascript library. Lodash provides many helpful functions for working with data types in JS, such as string functions, object handler functions, and array handler functions…
Why are you getting the error “Cannot find module ‘lodash’” in Javascript?
To use lodash, you must install it from npm. If you don’t have it installed but try to use lodash like the example below, the program will crash.
index.js file:
// import 'lodash' but not installed
const _ = require("lodash");
console.log(_.trim("#####learnshareIT#####", "#"));
// expected output: learnshareIT
Output:
Error: Cannot find module 'lodash'
How to fix this problem?
Install lodash before using it.
To fix this error, you just need to install lodash before using it. Open a command line interface in your project’s directory. And type:
npm install --save lodash
If you are working with typescript, then you must install @types/lodash by typing:
npm install --save @types/lodash
Next, check package.json:
{
"name": "my-express",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.18.2",
"lodash": "^4.17.21" // installed lodash
}
}
Like the above code, a lodash package in the dependencies proves you have successfully installed it. Now use it.
Let’s try the first example again, but this time we have installed lodash.
index.js file:
// import lodash
const _ = require("lodash");
console.log(_.trim("######learnshareIT#####", "#"));
// expected output: learnshareIT
Output:
learnshareIT
Clear cache if lodash is installed.
If you have lodash installed and in the dependencies also have lodash but still get the error “Cannot find module ‘lodash’” in Javascript, just clear the npm cache.
First, you should delete the node_modules folder and the package-lock.js file. Then run the following two commands:
npm cache clean -force
npm install
Once done, the node_modules folder and the package_lock.json file will be reinstalled. Like this:
Now use lodash wherever you want, and you will never get the error message “Cannot find module ‘lodash’” again.
Summary
You just discovered two ways to fix the error “Cannot find module ‘lodash’” in Javascript. We believe that if you encounter the same error with another library other than lodash, you can still fix it on your own without google. If you have any questions, please comment below.
Have a great day!
Maybe you are interested:
- “TypeError: then is not a function” in JavaScript
- “Cannot destructure Property of Undefined” in JavaScript
- “Cannot find module ‘date-fns’” in Javascript
- “Cannot Read Property ‘FindIndex’ Of Undefined” In JavaScript – How To Solve It?
Hi, I’m Cora Lopez. I have a passion for teaching programming languages such as Python, Java, Php, Javascript … I’m creating the free python course online. I hope this helps you in your learning journey.
Name of the university: HCMUE
Major: IT
Programming Languages: HTML/CSS/Javascript, PHP/sql/laravel, Python, Java
The “Cannot find module ‘lodash’” error occurs due to one of the following reasons:
-
The
lodash
module is not installed in the correct project directory. -
Using the module without installing it in the project.
-
Installed the module in a global context and trying to access in project local context.
To solve the error “Cannot find module ‘lodash’”, open the project root folder in your terminal and run the following command to install the lodash
module.
For TypeScript, you need to install the typings using the below command:
npm install --save-dev @types/lodash
Now, you can import and use the lodash module in your project like this:
const _ = require('lodash/lodash');
const a = _.join(['a', 'b', 'c'], '~');
console.log(a); // => 'a~b~c'
If you want to install a particular version of ‘lodash’ module, you can use the following command.
npm install lodash@4.17.21
If you’re still facing the error, then follow the below steps to resolve it.
- Remove the
node_modules
folder andpackage-lock.json
file, inside your project directory by using the below command.
rm-rf node_modules package-lock.json
or you can remove it manually by right-clicking on it and select the delete
option.
- Clear the npm cache.
- Re-install the node modules again by running the
npm install
command.
Verify now if you’ve installed it correctly or not by opening the package.json
file and check for lodash
module in the dependencies
object.
"dependencies": {
//...
"lodash": "^4.17.21",
//.. other packages
}
Conclusion
The can’t find module lodash error occurs, if you’re trying to access a lodash
module that is not currently installed in your project. To solve the error install the lodash
module in your project directory by running the npm install lodash
command.
If you use the TypeScript, you should install the typings by using the following command npm i @types/lodash --save-dev
.
В работе мне довольно часто приходится проверять какие-то небольшие сниппеты кода на различных входных данных. Такое возникает, например, когда я занимаюсь код ревью, и возникает желание убедиться в правильной обработке краевых условий. Либо же просто, когда я использую при разработке какую-то внешнюю библиотеку, и мне нужно быть уверенным, что использованный метод будет работать ожидаемо.
Для таких проверок и приходит на помощь CLI-среда REPL (read-eval-print-loop), которая по сути является неким инлайн-интерпретатором, в нём вы можете написать строку кода и тут же увидеть результат.
Чтобы запустить REPL Node.js, достаточно просто набрать в терминале:
node
В нём легко выполнять какие-то простые вещи и сразу видеть результат:
> [1, 2, 3].join(':')
'1:2:3'
REPL и библиотеки
Давайте представим, что мы попали в следующую ситуацию: нам понадобилось посмотреть, как именно ведёт себя функция библиотеки lodash keyBy. Мы наивно пробуем:
> _.keyBy([{ id: 1, name: 'Justin' }, { id: 2, name: 'Bob' }], 'id')
TypeError: Cannot read property 'keyBy' of undefined
Естественно, никакой магии нет, мы никак не обозначили, что собираемся использовать lodash в REPL, да и более того, lodash у нас не установлена глобально, и REPL просто не может её увидеть. Что ж, ставим:
yarn global add lodash
# или
npm i -g lodash
И пробуем запустить REPL, но в этот раз сделаем это несколько хитрее:
node -i -e "const _ = require('lodash')"
И видим Error: Cannot find module 'lodash'
. Давайте пока отложим эту неприятность и посмотрим, какими ключами мы воспользовались:
-e "const _ = require('lodash')"
выполняет указанный код, в данном случае импортирует модуль lodash в константу_
.-i
форсирует интерактивный режим, нам это необходимо, так как предыдущий ключ-e
подразумевает под собой только выполнение кода, без интерактивного режима.
С ключами разобрались, но почему же не видна библиотека, мы же поставили её глобально? Тут стоит проверить, а верно ли указана переменная окружения NODE_PATH
. В моём случае она не была установлена вообще, и пришлось её добавить в конфиги шелла (в моём случае это был fish), указав в ней путь до глобальных модулей:
set -x NODE_PATH ~/.config/fnm/lib/node_modules
Эта переменная может задаваться по-разному, если у вас, например, bash или zsh, и в зависимости от того, пользуетесь ли вы nvm или fnm. Если вдруг у вас возникнут трудности на этом этапе, не стесняйтесь задавать вопросы, будем разбираться вместе!
Итак, пробуем снова:
node -i -e "const _ = require('lodash')"
И, наконец, попадаем в REPL без ошибок, с надеждой снова пробуем функцию из lodash:
> _.keyBy([{ id: 1, name: 'Justin' }, { id: 2, name: 'Bob' }], 'id')
{ '1': { id: 1, name: 'Justin' }, '2': { id: 2, name: 'Bob' } }
И, всё заработало! Мы добились того, чтобы при запуске нашей песочницы нам подключалась библиотека и мы могли свободно ей пользоваться.
Также хотелось бы отметить, что это далеко не единственный и даже не самый простой способ использовать внешние библиотеки в REPL. Например, есть trymodule, который довольно просто позволяет открывать REPL с импортированными библиотеками. Но честно говоря, в моём случае я столкнулся с небольшими субъективным недостатками, поэтому пока остаюсь на нативном REPL.
Итак, подытожим, мы с вами научились из Node.js создавать свою песочницу для различных проб и экспериментов.
Ссылки
- Документация к REPL-режиму Node.js
- trymodule
There are two ways to install npm packages: locally or globally. Choose which kind of installation to use based on how you want to use the package.
- If you want to depend on the package from your own module, using something like Node.js’
require
, then you want to install locally. This isnpm install
‘s default behavior. - If you want to use a package as a command line tool, (such as grunt CLI), then install it globally.
To learn more about the install
command, check out the CLI doc page.
Installing a Package
A package can be downloaded with the command:
> npm install <package_name>
This will create the node_modules
directory in your current directory (if one doesn’t exist yet) and will download the package to that directory.
Test:
To confirm that npm install
worked correctly, check to see that a node_modules
directory exists and that it contains a directory for the package(s) you installed.
Example:
Install a package called lodash
. Confirm that it ran successfully by listing the contents of the node_modules
directory, where you should see a directory called lodash
.
Microsoft Windows:
C: npm install lodash C: dir node_modules #=> lodash
macOS, Ubuntu, Debian
> npm install lodash > ls node_modules #=> lodash
Which Version of the Package is Installed?
If there is no package.json
file in the local directory, the latest version of the package is installed.
If there is a package.json
file, npm installs the latest version that satisfies the semver rule declared in package.json
.
Using the Installed Package in Your Code
Once the package is in node_modules
, you can use it in your code. For example, if you are creating a Node.js module, you can require
it.
Example:
Create a file named index.js
, with the following code:
// index.js var lodash = require('lodash'); var output = lodash.without([1, 2, 3], 1); console.log(output);
Run the code using node index.js
. It should output [2, 3]
.
If you had not properly installed lodash
, you would receive this error:
module.js:340 throw err; ^ Error: Cannot find module 'lodash'
To fix this, run npm install lodash
in the same directory as your index.js
.
Be sure to install lodash in the required folder. This is probably your C:gwsk directory.
n
If that folder has a package.json file, it is also best to add –save behind the install command.
n
$ npm install lodash --saven
n
The package.json file holds information about the project, but to keep it simple, it holds your project dependencies.
n
The save command will add the installed module to the project dependencies.
n
If the package.json file exists, and if it contains the lodash dependency you could try to remove the node_modules folder and run following command:
n
$ npm cache clean n$ npm installn
n
The first command will clean the npm cache. (just to be sure)nThe second command will install all (missing) dependencies of the project.
n
Hope this helps you understand the node package manager a little bit more.
‘
I found deleting the contents of node_modules and performing npm install
again worked for me.
‘
node.js – cannot find module lodash
Maybe loadash needs to be installed. Usually these things are handled by the package manager. On your command line:
n
npm install lodash n
n
or maybe it needs to be globally installed
n
npm install -g lodashn
‘
I was working with angular
project and was using node
for the server and package dependies.
After doint some package installing.
npm install
was installing all the dependies.
so, i removed my node_modules folder
did again npm install
and running gulp task gave me error.
[14:50:36] 'build:javascripts:templates' errored after 698 ms
[14:50:36] Error: Cannot find module 'lodash._reinterpolate'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/Lokesh/Documents/
What to do? Tried everything and then
found the solution.
{sudo -H} npm i -g npm
npm i --save lodash._reinterpolate
Both solved my problem.
npm-schrinkwrap.json file ???
For the production we use npm-schrinkwrap.json
file. this holds all the dependies for the project its just like package.json
lock.
Note: when we do
npm install <package> --save #will not change the `schrinkwrap`
//run
npm schrinkwrap
//now the npm-schirnkwrap will be updated