How can I import lodash library in my Vanilla JS file

Viewed 15

I have installed the "lodash" using "npm install --save lodash" and imported in my JS file.My intention is to Deep clone of an Object and found that Lodash is the library which solve this problem. My HTML and JS files are as follows.

My HTML file is as follows.

<!DOCTYPE html>
<html lang="en">
<body>
 <script type="module" src="scripts.js" ></script> 
</body>
</html>

My JS file (scripts.js) is as follows:

import _ from 'lodash';

let userOne = {
 name: "Siju",
 userFunction:function(){
  return this.name;
 } 
};
 
// Deep Copy: Start
let userTwo=_.cloneDeep(userOne);
// Deep Copy: End

userTwo.name="Johnson";
userTwo.userFunction=function(){ return this.name.length }

console.log(userOne.name);
console.log(userTwo.name);
console.log(userOne.userFunction());
console.log(userTwo.userFunction());

But i am getting following errors.

Error1: (When use: import _ from 'lodash';) Uncaught TypeError: Failed to resolve module specifier "lodash". Relative references must start with either "/", "./", or "../".

Error2: (When use: import _ from './node_modules/lodash';) Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

I have spend lot of time on this and did'nt get any suitable solution. I am really frustrated on this issue because it is a silly issue but did'nt get any proper fix in the internet. Most of the explanation is seems to be with so many dependency fixes and all. But no any fixes are worked for me. So anyone can be come up with simple and proper fix for this. Thank You Very Much in Advance!

1 Answers

You can go to http://lodash.com/ and download the entire .js file into your current project folder and then include the following line in your HTML body paragraph.

<script src="lodash.js"> </script>

And then import it at the top of your JavaScript file in which you would like to use it.

import _ from 'lodash'

Related