What is “require”?

Andrew Park
2 min readJun 27, 2021

You may have seen a statement with “require” command, as an example below in ”script.js” file. First time I saw it, it threw me off.

CommonJS modules

In the above example, addTwo and multiplyTwo functions are exported from “twoNumbers.js” file/module using module.exports. And then exported functions are imported into “script.js” file/module using “require“ command.

These modules are written as CommonJS modules, and “require” command is used to import exports from CommonJS modules.

ES modules:

Within ES modules, “import” statement is used instead of “require” to import exported items from ES modules.

In the ES module example below, addTwo and multiplyTwo functions are exported from “twoNumbers.js” file/module using exports command. And then exported functions are imported into “script.js” using ”import“ command.

ES6 module

Export syntax:

\\ CommonJS export:module.exports.addTwo = function (num1, num2) {
return num1 + num2;
};
\\ ES modules export:export const addTwo = function (num1, num2) {
return num1 + num2;
};

Import syntax:

\\ CommonJS import (importing from "twoNumbers.js"):const { addTwo } = require("./twoNumbers.js");\\ ES modules import (importing from "twoNumbers.js"):import { addTwo } from "./twoNumbers.js";

So, now you know what “require” is trying to do.

--

--