JavaScript require vs import

In this article let us understand what JavaScript require() and import() statements do, how they fetch modules, and their differences. We will begin by understanding what a JavaScript module is, in the first place.

JavaScript module is a file that contains a few lines of code written in JavaScript. They are the same as JavaScript Libraries. Modules often contain a class or a library of functions that are used for a specific purpose. These can be called with the help of require and import statements. The use of modules reduces the number of lines of code in one’s program/script. A major advantage of modules is that functions of another module can be called without writing the body of the functions themselves.

Some of the common modules are:

CommonJS, AMD, RequireJS, ES(ECMAScript)6 Modules. Refer to this medium article for an in-depth explanation of how these modules are different.

Table of Contents


Syntax and explanation

1) require()

In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object. require() statement not only allows to add built-in core NodeJS modules but also community-based and local modules.

Syntax:

To include a module, the require() function is used with the name of the module:

var myVar = require('http'); //to use built-in modules
Var myVar2 = require('./myLocaModule') to use local modules


2) import()

import() & export() statements are used to refer to an ES module. Other modules with file types such as .json cannot be imported with these statements. They are permitted to be used only in ES modules and the specifier of this statement can either be a URL-style relative path or a package name. Also, the import statement cannot be used in embedded scripts unless such script has a type="module". A dynamic import can be used for scripts whose type is not “module”

Syntax:

var myVac = import("module-name");


How is require() different from import()

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file.

To use the require() statement, a module must be saved with .js extension as opposed to .mjs when the import() statement is used.

ES modules can be loaded dynamically via the import() function unlike require().