15

I would simply like to use the functions from Lodash on my website.

I included this in the <head> section:

<script scr="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

What else should I do? I tried to add:

<script>
    var _ = require('lodash');
</script>

But I get the following error:

Uncaught ReferenceError: require is not defined

2
  • 3
    You don't need require. You use _ directly. Since you've incuded the js file, you can use it like you do with jquery. Jun 5, 2018 at 14:14
  • 3
    also it's src not scr Jun 5, 2018 at 14:15

2 Answers 2

26

If you load in Lodash using a script tag, the script will automatically expose the _ function, and you can directly use it after including it in the document:

document.querySelector("body").onload =
    function() {console.log(_.sample([1, 2, 3, 4]))}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

No need to require the function.

0
-2

Use:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<script src="lodash.js"></script>

Put these two lines of code in head, and you are ready to use Lodash in your JavaScript files.

1
  • not working. I want to use lodashjs in javascript file. I want to use compose function. Can someone help?
    – sudhanshu
    Mar 2, 2022 at 2:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.