Skip to main content

Command Palette

Search for a command to run...

require() vs import() Functions in JavaScript

Published
2 min read
S

React js developer

The require and import functions/statements are used to include modules within your JavaScript file, but they possess some differences. The two major differences are:

The require() function can be called from anywhere within the program, whereas import() cannot be called conditionally. It always runs at the beginning of the file.

To include a module with the require() function, that module must be saved with a .js extension instead of .mjs when the import() statement is used.

In JavaScript, modules refer to a file that holds JavaScript code which performs a specific purpose.

Modules are self-contained, making it easy to add, remove, and update functionalities without affecting your entire code because they are decoupled from other pieces of cod

When you have these modules in separate JavaScript files, you'll want to use them within the original JavaScript file.

what the require() function does, how you can use it?

In the browser, JavaScript module execution depends upon import and export statements. These statements load and export ES modules, respectively. This is the standard and official way to reuse modules in JavaScript, and it’s what most web browsers natively support.

What is the JavaScript require() Function?

The require() function is a built-in CommonJS module function supported in Node.js that lets you include modules within your project. This is because, by default, Node.js treats JavaScript code as CommonJS modules.

The require() function is straightforward to use and understand, as all you have to do is assign the function to a variable.

In this function, you will pass the location name as an argument. Here is the general syntax:

const varName = require(locationName);

Suppose you have a CommonJS module that exports a function *getFullName* as seen below:

// utils.js

const getFullName = (firstname, lastName) => {

return `My fullname is ${firstname} ${lastName}`;

};

module.exports = getFullName;

Then you can use the require() function to use/include this module within your JavaScript file:

// index.js

const getFullName = require('./utils.js');

console.log(getFullName('John', 'Doe')); // My fullname is John Doe

The module is located within a local file in the above code, which is why the local address is referenced using the file name.

But in a situation when you want to include an external module from the web, then you make use of the web-based location:

const myVar = require('http://web-module.location');

More from this blog