+1 (252) 631 8899 +91 98212 12676

Difference between JavaScript "require" vs "import"

August 27, 2023

JavaScript, Web Development

Sumeet Shroff
By Sumeet Shroff
Difference between JavaScript "require" vs "import"

Both require and import are mechanisms used to include and use code from other files or modules. However, they are associated with different module systems and have some key differences. Let's go over each one and explain their differences:

CommonJS require:

require is a keyword used in CommonJS, which is a module system primarily used in server-side JavaScript (Node.js). It is a synchronous approach to including modules. Here's how it works:

const module = require('./module');

Synchronous Loading: When require is used, the module is loaded synchronously. This means that the execution of code will pause until the required module is fully loaded and returned. This can potentially block the main thread in certain scenarios.

Dynamic Loading: require supports dynamic loading of modules. This means that you can use variables or expressions as the module path.

Single Default Export: In CommonJS, modules generally export their values using module.exports. When you use require, you get the value exported using module.exports directly.

ES6 import:

import is a syntax introduced in ECMAScript 2015 (ES6) to support module loading in modern browsers and environments that support ES6 modules. It's designed to be more flexible and asynchronous. Here's how it works:

import module from './module';

Asynchronous Loading: The import statement is asynchronous. It doesn't block the main thread and instead works in the background, allowing other parts of your code to continue execution.

Static Loading: The import statement doesn't support dynamic loading like require. The module path must be a string literal and cannot be generated dynamically.

Multiple Named Exports: ES6 modules can export multiple values using named exports. When you use import, you can specify which exported values you want to import.

Default and Named Imports: You can have both default and named imports in a single import statement:

import defaultExport, { namedExport1, namedExport2 } from './module';

In summary, the main differences between require and import are the module systems they belong to, their loading behavior (synchronous vs. asynchronous), and the support for dynamic loading and multiple named exports. If you're using Node.js, you'll typically use require, whereas in modern front-end development, you'll use import for ES6 modules.

Sumeet Shroff

Sumeet Shroff

Loading...

Get 20% off on your first order

Get Started Now