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/lodash@4.17.10/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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mat
  • 2,412
  • 5
  • 31
  • 69

2 Answers2

25

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/lodash@4.17.15/lodash.min.js"></script>

No need to require the function.

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
-2

Use:

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • not working. I want to use lodashjs in javascript file. I want to use compose function. Can someone help? – sudhanshu Mar 02 '22 at 02:54