How to use CommonJS require syntax In Javascript

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.

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

Output:

[ 3, 5 ]

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:

Table of Content

  • Using ES6 import syntax
  • Using CommonJS require syntax

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

npm i lodash

Similar Reads

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....

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....

Contact Us