Open In App

How to Import a Single Lodash Function in JavaScript ?

In JavaScript, we have to import various functions for operation, but importing a single function is also important for optimizing code and reducing unnecessary dependencies.

Below are the approaches to importing a single Lodash function in JavaScript:

Run the below command before running the below code on your system:

npm i lodash

Using ES6 import syntax

In this approach, we are using ES6 import syntax to directly import the compact function from the Lodash library, allowing us to use it directly without referencing the entire Lodash library.

Syntax:

import functionName from 'lodash/moduleName';

Example: The below example uses ES6 import syntax to import a single lodash function in Javascript.

import compact from 'lodash/compact';
let arr = [1, null, 3, null, 5];
let res = compact(arr);
console.log(res); 

Output:

[1, 3, 5]

Using CommonJS require syntax

In this approach, we are using CommonJS require syntax to import the compact function from the Lodash library, which is common in Node.js environments and allows us to use Lodash functions in JavaScript code.

Syntax:

const functionName = require('lodash/moduleName');

Example: The below example uses CommonJS require syntax to import a single lodash function in Javascript.

const compact = require('lodash/compact');
let arr = [null, null, 3, null, 5];
let res = compact(arr);
console.log(res);

Output:

[ 3, 5 ]
Article Tags :