The Basics of require()

Tina Huynh - Apr 14 '22 - - Dev Community

Table of Contents

  1. What is JavaScript "require"?
  2. JavaScript require vs import
  3. Helpful Links

What is require

require() is in Node.js, not the standard JavaScript API, and its a built-in function to load modules.

What are modules?

A module is a function or group of similar functions that are grouped together within a file and contain the code to execute a very specific task. Modules are created in order to organize and structure code. The main principles of modules include being:

  • independent / self-contained
  • specific towards a single or related group of tasks
  • reusable in order to be integrated into other programs

Each module has its own scope, similar to variables. A module cannot directly access information or data that had been defined in another module unless that module chooses to expose that particular data. To expose certain data, they must be assigned to exports or modules.exports and it must use require().

What require would look like:

const express = require('express')
const app = express()
Enter fullscreen mode Exit fullscreen mode

The above code would load the express module, a minimal framework that provides a set of common utilities for building servers and web applications. Before using the express module, it also needs to be downloaded through npm install express, a command that lets you download packages.

require vs import

import() and export() statements are used to refer to an ES module. The import statement cannot be used in embedded scripts unless the respective script has a type="module". On the other hand, a dynamic import can be used for scripts whose type is not "module".

How are they different?

1. Where they can be called from

Although require() can be called anywhere inside the program, import() cannot be called upon conditionally. It must be included at the beginning of the file.

2. Working with modules

require() is used with NodeJS to read and execute CommonJS modules while import() can't be used outside ES modules.

3. Synchronous or asynchronous

import() statements are asynchronous and are known to perform well compared to require() functions in large-scale applications.

4. Future applications

The ES module system is adopted by TypeScript and was introduced as the standard to maintain Client-side JavaScript modules.

Helpful Links

Happy coding!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .