Search code examples
javascriptnode.jsimportlodashrequire

Lodash import gives error in Node.js project


I'm just starting to experiment with Node.js and Object Oriented Programming in Javascript.

This is my node based project structure enter image description here

This is my package.json file: enter image description here

I'm trying to use lodash in my app.js file. For that, I'm trying to do :

import * as _ from "lodash";

but this gives me error: enter image description here

I tried another approach first to import lodash using :

var _ = require('lodash');

But this also gave me an error: enter image description here

I'm trying to understand what's the difference in the two imports(I think the 1st one is the way to do it in ES6 modules approach). Which one is used when. And why does it not work in my application? What is the correct way to use lodash in my application? I'm sure these are pretty basic questions but everywhere I'm looking, it shows one of the above two approaches to load lodash and they're not working for me.


Solution

  • For any javascript code that gets executed in the browser and requires lodash the easiest way to do it is just to have a <script> tag in your html before your code runs:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

    Then you don't need to require or import lodash in your app.js file. The example above loads lodash from an external CDN. To load it from your own application just change the src attribute to point to where your node.js app is serving the lodash library from.

    If you want to use require or import statements in your client javascript code there are build tools and transpilers that replace the require or important statements in your source code to code that will work in the browser. This is saved into another file and then you run that file in your browser. Browserify, Webpack and Babel are some you might want to look into, but if you are just starting out you may want to do that sometime down the road when you are building more complex applications.