Importing modules in JS

Viewed 108

I got a problem that I struggle with for a long time and it's about importing modules to my main JS script.

I downloaded a lodash library via npm and I want to import it into my main script in order to use its functionalities. Here's the code:

import * as _ from './node_modules/lodash/lodash.js';

console.log(_.head([1,2,3]))

However, when I'm running the script I receive such an error:

!  ▶ Uncaught TypeError: _.head is not a function
        <anonymous> http://127.0.0.1:5500/playground.js:43
      [Więcej informacji]
>> _.head([1,2])
<- 1

As you can see, I cannot use _.head in the script, but I can use it from the console, which - I think - means that lodash was imported correctly.

What might be the cause of this problem? Also, I don't know if it's just me or is importing modules really such a painful thing to do? Maybe you can recommend some articles on this topic? Thank you for all the replies in advance

1 Answers

You don't need or probably want that path. If you've installed lodash via npm, yarn, or another package manager, use:

import _ from "lodash";

or possibly

import * as _ from "lodash";

depending on how lodash handles its exports.

Related