How to Integrate lodash in Angular and typescript application

Other related posts lodash library in my previous article.

This article covers steps to integrate into an Angular application.

Some steps are required to integrate third-party libraries into Angular applications.

with this, You can use utility functions in angular projects.

It explains the existing application that generates an application using an angular CLI code generator tool.

The below steps will work on all Angular versions.

Now go to the project directory and install the lodash library.

Install and setup lodash

Lodash has provided npm and yarn installer.

First, install your project using the below command based on your package manager.

npm install --save lodash
yarn add lodash

It creates the following entry in package.json.

"dependencies": {
    "lodash": "^4.17.21",

It adds lodash dependencies installed into your projectdirectory/node\_modules/lodash folder.

Install types lodash definition file

The next step is to Configure the typescript definition file.

Lodash is a javascript library, Angular is based on typescripts. So you need to provide typescript definition files. The extension of This file always ends with d.ts.

This file contains type-checking information of javascript objects.

package for typing is @types/lodash.

if you don’t know typing information for a specific library, you can check the Microsoft typing tool.

npm install --save @types/lodash
yarn add @types/lodash

Once the lodash and typing definition file is installed successfully, You need to do code changes as below.

angular Component lodash changes

You don’t need any code changes at the module level, instead, you can do changes in your component.

Instead of the component, the Best way is to write a utility service that is a wrapper for this module. so that components and modules are loosely coupled. import all classes and methods from the module into this component.

Now you can able to call any function on Underscore.

import * as _ from "lodash";
export class AppComonent implements OnInit {
  ngOnInit() {
    console.log(_.isEmpty({})); // returns true