J160 Use of an External Module (in Node)
An elementary exercise to understand how to use an external module, Lodash, in a JS file run through Node.js. It requires some setup steps.
Objective: You will set up a basic Node.js project, import the Lodash library, and then utilize one of its utility functions to process a string.
Setup steps:
-
Create a new directory: Create a new folder on your system to house your Node.js project.
-
Initialize npm: Open your terminal or command prompt, navigate to your project directory, and type
npm init -f. This command initializes a new npm project and creates apackage.jsonfile with default values. -
Install Lodash: Still in your terminal or command prompt, type
npm i lodash --save. This will fetch the Lodash library from npm and save it as a dependency in yourpackage.jsonfile. -
Add IntelliSense Configuration: Create a new file in your project directory named
jsconfig.json. Add the following content to that file:
This configuration will improve your coding experience by providing IntelliSense for imported modules, such as Lodash.
- Implementing Lodash:
Create a file named
app.jsin your project directory. At the top of this file, type:
This line imports the Lodash library, making its functions accessible via the _ variable.
Tip
With Lodash imported, you can now use any of its utility functions within your app.js file.
Solution
To run the code, navigate to your project directory in the terminal or command prompt and type node app.js. You should see the capitalized “Mikkel” printed to the console.
For further exploration, you can visit the Lodash documentation to discover the wide variety of utility functions Lodash provides.