Explaining the Ultimate Difference Between Node.js require vs ES6 import

Node.js allows you to use different modules in our application. When using different modules we might have come across two keywords: require and import, both of which are used to import the modules and packages into our project.

In this article, we will understand the difference between the two ways of importing modules in Node.js i.e using require and import functions by understanding their meaning and usage in Node.js applications. We will also cover some basics related to CommonJS and ECMAScript modules that will help us better understand the two keywords.

What are modules in Node.js?

A module in Node.js is generally a collection of JavaScript files and folders containing related files defined by a package.json that provides some functionalities to other Node.js applications by exporting some functions, exposing APIs, and allowing code reusability.

Node.js has mainly two module systems:

  • CommonJS modules
  • ECMAScript modules

We will be discussing both these module systems when we talk about the require and import keywords.

Modules in Node.js can be categorized into three types:

  • Core Modules: These are built-in modules like buffer, http, fs, etc.
  • Local Modules: These types of modules are locally created by the programmer for specific use in their program.
  • Third-Party Modules: These modules are made by other programmers and are available to use and install through package managers like npm and yarn. Example: express, loadash, etc.

Here is a more extensive guide to different types of Node.js modules.

Now let’s get into understanding the two types of import statements: require and import

Node.js require statement

Node.js require statement provides the easiest way to import any modules in our application. It is used by the CommonJS module system which is the default module system in Node.js. CommonJS is the standard way to package JavaScript code for Node.js or server-side apps. To use the CommonJS syntax, our package.json file may or may not contain a “type” key at the top level.

When the require statement is called, Node.js follows the following sequence of steps to load the module:

  1. Resolving: Node.js tries to get the absolute path of the module by first looking into the core modules, and then inside node_modules. If an absolute path is already provided, Node.js tries to resolve that path instead of looking into the core modules or the node_modules folder.
  2. Loading and Wrapping: Node.js loads the file and wraps the module code in a special function that will give us access to some objects.
  3. Execution: Node.js executes the module code wrapped in the function and provides us with the exported functions, objects, and variables.
  4. Caching: Node.js even caches the module code for further use in the application.

The require function takes in an argument which can be an ID or a path. The ID refers to the id (or name) of the module needed.

Node.js require statement to import third-party modules

Core modules generally do not require to be imported while third-party modules installed inside the node_modules folder need to be imported using the following syntax.

Syntax:

const module = require('module_name')

Example:

const express = require('express')

Node.js require statement to import local modules

Local modules can be loaded by providing an absolute or relative path or a folder path

Syntax:

// Syntax for absolute path
const module = require('/<folder1>/<folder2>/.../module')

//Syntax for relative path
const module = require('./<module_name>')

Example:

const passwordHash = require('/nodeproject/utils/passwordHash.js')

//or 

const hello = require('./helloWorld.js')

Node.js import statement

Node.js import function is used for importing an ECMAScript or ES module. ECMAScript is the standard way to package JavaScript code for use in Browsers and other JavaScript runtimes. Node.js doesn’t use ES syntax directly but it can be used if the file extension for the module is ‘.mjs’ or the module’s nearest parent folder has { “type”: “module” } in its package.json file.

Unlike the require function, the import function uses an asynchronous method to load the module, and similar to the require function, the import function can also use relative and absolute specifiers. Import also allows you to selectively import different exports by using object destructuring.

Syntax:

// Importing the entire module
import * as name from '<module_name>'

// Importing the default export from the module
import name from '<module_name>'

// Importing multiple exports from the module
import { name1, name2 } from '<module_name>'

// Importing module using relative specifier
import * as name from './<folder1>/<folder2>/.../<module_name>'

Example:

import * as Utils from 'app.js'
import react from 'react'
import { useState, useEffect } from 'react'

Difference between require and import

requireimport
It is used with the CommonJS module systemIt is used in the ECMAScript version 6 or ES6 module system
Synchronous loading of modules (i.e modules are loaded sequentially)Asynchronous loading of modules (i.e Node.js does not wait for the previous module to complete import)
Less efficient due to synchronous loading of modulesMore efficient and performant due to the asynchronous loading of modules
Memory usage is more as the entire module is importedObject destructuring can be used to selectively import pieces of code or named exports
It imports the components exported using module.exports keyword in the moduleImports the components exported using the export keyword in the module
require is the default way of importing as CommonJS is the default module systemES6 or ECMAScript module system needs to be enabled to use the import statement
require can be called anywhere in the programimport needs to be called at the top of the program
used generally with server-side node applicationsused generally with Browser or front-end focused application

Conclusion

In this article, we differentiated the two most common ways of importing modules into Node.js i.e using require and import functions. We understood the two module systems namely CommonJS and ECMAScript and the three types of modules in Node.js and learned how we could import each of them using the require and import statements.

References

https://nodejs.org/docs/latest/api/modules.html

https://nodejs.org/api/esm.html

Devdeep Ghosh
Devdeep Ghosh
Articles: 14