JavaScript

What Is the Difference Between require() and import in JavaScript?

In JavaScript, require() and import are used to include functionality from other modules. They help developers organize code into reusable files instead of…

D
DevByteTechnical Author
Published
15 min read1 views
What Is the Difference Between require() and import in JavaScript?

If you have worked with Node.js, you have probably seen both require() and import in JavaScript code.

For example, you might have written something like this in a Node.js project:

const express = require("express");

But in another project, especially one built with React, Next.js, or modern JavaScript tooling, you might see:

import express from "express";

Both statements allow you to use code from another module, but they belong to different module systems.

This can be confusing when you are switching between an older Node.js project and a modern application. You might wonder whether import is simply a newer version of require(), whether one is faster, or why one works in your project while the other throws an error.

The short answer is that require() is associated with CommonJS, while import is part of the ECMAScript Modules (ESM) system. Both are used to work with modules, but they have different syntax, loading behavior, and configuration requirements.

In this blog, we will understand how both work, when to use each one, and how to avoid common module-related errors in Node.js projects.

What Is require() in JavaScript?

require() is the traditional way to load modules in Node.js. It belongs to the CommonJS module system, which was widely used in Node.js before native ECMAScript Modules became available.

With CommonJS, you use require() to load a module and module.exports or exports to expose functionality from a file.

Let's start with a simple example.

Imagine you are building a Node.js application and want to keep your mathematical functions in a separate file.

math.js

function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

module.exports = {
  add,
  subtract,
};

Here, we have created two functions and exported them using module.exports.

Now, let's use those functions in another file.

app.js

const math = require("./math");

console.log(math.add(10, 5));
console.log(math.subtract(10, 5));

Output:

15
5

When Node.js executes require("./math"), it loads the CommonJS module and returns the value exported through module.exports.

You can also import only the functions you need through destructuring:

const { add, subtract } = require("./math");

console.log(add(10, 5));
console.log(subtract(10, 5));

This is convenient when you have a utility file containing many functions but need only a few of them.

How Does require() Work?

In a typical CommonJS Node.js project, require() loads a module synchronously.

When Node.js encounters a statement such as:

const fs = require("node:fs");

it loads or retrieves the cached CommonJS module and returns its exported value.

CommonJS modules are generally evaluated the first time they are loaded. Subsequent require() calls for the same resolved module usually return the cached exports rather than executing the module again.

For example:

// logger.js

console.log("Logger module loaded");

module.exports = {
  log(message) {
    console.log(message);
  },
};

Now use it in another file:

const logger = require("./logger");
const anotherLogger = require("./logger");

logger.log("First message");
anotherLogger.log("Second message");

For the same resolved module, the output is typically:

Logger module loaded
First message
Second message

The module's top-level code normally runs only once because Node.js caches the loaded CommonJS module.

This caching behavior can be useful for shared utilities and configuration modules. However, it also means that changes to a module's exported object can sometimes be visible to other parts of the application that use the same cached module.

What Is import in JavaScript?

import is the standard module syntax introduced by ECMAScript Modules, commonly called ESM.

It allows you to import functions, variables, classes, and other exports from another module.

You will frequently see it in modern JavaScript projects, including React, Next.js, TypeScript, and current Node.js applications.

Let's rewrite our previous example using ESM.

math.js

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

Instead of using module.exports, we use the export keyword to make functions available to other modules.

Now let's import those functions.

app.js

import { add, subtract } from "./math.js";

console.log(add(10, 5));
console.log(subtract(10, 5));

Output:

15
5

Notice that we are importing the functions by their exported names.

This is called a named import.

ESM also supports default exports.

For example:

greeting.js

export default function greet(name) {
  return `Hello, ${name}!`;
}

You can import the default export like this:

import greet from "./greeting.js";

console.log(greet("Manjeet"));

Output:

Hello, Manjeet!

A default export represents the module's primary exported value, while named exports let a module expose multiple individually named values.

One important difference is that the name used for a default import can be chosen by the importing file. Named imports, on the other hand, generally need to match the exported names.

For example:

import sayHello from "./greeting.js";

This is valid because greet is the default export, and we have chosen to refer to it as sayHello in the importing module.

Difference Between require() and import

Now that we understand both approaches, let's compare them.

Feature

require()

import

Module system

CommonJS

ECMAScript Modules (ESM)

Syntax

const fs = require("node:fs")

import fs from "node:fs"

Loading behavior

Synchronous module loading

Static imports are resolved and linked through the ESM module system

Export syntax

module.exports or exports

export or export default

Named exports

Often accessed through object properties or destructuring

Supported directly with named imports

Conditional loading

Can be called inside functions and conditions

Static imports must appear at module top level; dynamic import() can be used conditionally

Top-level await

Not supported directly in ordinary CommonJS files

Supported in ESM

Tree-shaking

Less straightforward for many build tools to analyze

Static imports and exports are generally easier for build tools to analyze

Common use

Existing CommonJS Node.js projects

Modern JavaScript and ESM-compatible Node.js projects

There is one detail worth understanding: saying that import is asynchronous would be misleading.

Static ESM imports are not ordinary asynchronous function calls. They are part of the module structure, and the runtime resolves and links modules before evaluating their dependent code.

The dynamic import() function, however, returns a promise and can be used when you need to load a module on demand.

Let's look at that distinction in more detail.

1. The Loading Behavior Is Different

One of the main differences is how the two systems load modules.

With CommonJS, you can call require() inside a function:

function loadLogger() {
  const logger = require("./logger");
  logger.log("Logger loaded");
}

loadLogger();

This works in a CommonJS file because require() is a function available in that module environment.

You can also use it conditionally:

if (process.env.NODE_ENV === "development") {
  const debugTools = require("./debug-tools");

  debugTools.enable();
}

The require() call is reached only if the condition is true.

Static ESM imports work differently.

You cannot put a static import declaration inside an ordinary if statement or function body:

if (process.env.NODE_ENV === "development") {
  // SyntaxError: static import declarations cannot be used here
  import debugTools from "./debug-tools.js";
}

Static imports belong at the top level of the module.

If you want to load a module conditionally in ESM, use dynamic import():

if (process.env.NODE_ENV === "development") {
  const debugTools = await import("./debug-tools.js");

  debugTools.enable();
}

The await works here if the code is inside an async function or in an ESM module where top-level await is supported.

You can also write:

async function loadDebugTools() {
  const debugTools = await import("./debug-tools.js");

  debugTools.enable();
}

Dynamic imports return a promise that resolves to a module namespace object.

This makes them useful for optional features, large modules that are not needed immediately, and conditional loading.

2. The Export Syntax Is Different

Another difference is how you expose functionality from a file.

With CommonJS:

// user.js

function getUser() {
  return {
    id: 1,
    name: "Manjeet",
  };
}

module.exports = getUser;

Import it using:

const getUser = require("./user");

console.log(getUser());

With ESM, you can write:

// user.js

export default function getUser() {
  return {
    id: 1,
    name: "Manjeet",
  };
}

And import it using:

import getUser from "./user.js";

console.log(getUser());

Both approaches can expose a single function, but the syntax and module semantics are different.

Be careful not to confuse module.exports with exports.

In CommonJS, exports is initially a reference to module.exports. This means the following works:

exports.getUser = function () {
  return { id: 1, name: "Manjeet" };
};

But this does not behave as many beginners expect:

exports = function () {
  return { id: 1, name: "Manjeet" };
};

Reassigning exports does not replace module.exports. To export a function directly, use:

module.exports = function () {
  return { id: 1, name: "Manjeet" };
};

This distinction matters when maintaining older Node.js applications.

3. Named Imports and Default Imports

ESM supports two common ways of importing exported values.

Named imports

A module can export several named functions:

// userService.js

export function getUser() {
  return { id: 1, name: "Manjeet" };
}

export function deleteUser() {
  return "User deleted";
}

Import both functions:

import { getUser, deleteUser } from "./userService.js";

console.log(getUser());
console.log(deleteUser());

You can import only one of them:

import { getUser } from "./userService.js";

Default imports

A module can also have one default export:

// config.js

export default {
  port: 3000,
  environment: "development",
};

Import it like this:

import config from "./config.js";

console.log(config.port);

A module can have both named exports and a default export, but it can have only one default export.

With CommonJS, there is no separate default export syntax built into the module system. A module can export an object containing several properties or export a single value directly through module.exports.

For example:

// config.js

module.exports = {
  port: 3000,
  environment: "development",
};

Then:

const config = require("./config");

console.log(config.port);

Both approaches can organize application code effectively. The important thing is to understand which module system your project uses.

4. How Do You Use require() and import in Node.js?

This is where developers often run into problems.

You might create a new file, write an import statement, and run it with Node.js, only to see a module-related error.

The reason is that Node.js supports both CommonJS and ESM, but it needs to know how to interpret your files.

Using CommonJS in Node.js

A traditional CommonJS project might look like this:

my-app/
├── package.json
├── app.js
└── math.js

Your package.json might contain:

{
  "name": "my-app",
  "version": "1.0.0"
}

The app.js file can use:

const math = require("./math");

console.log(math.add(10, 5));

And math.js can export functions using module.exports.

Run the application:

node app.js

In the absence of configuration indicating otherwise, .js files in this example are treated as CommonJS under the traditional default configuration.

Using ESM in Node.js

For a modern ESM project, add "type": "module" to package.json:

{
  "name": "my-app",
  "version": "1.0.0",
  "type": "module"
}

Now you can use import and export in .js files.

math.js

export function add(a, b) {
  return a + b;
}

app.js

import { add } from "./math.js";

console.log(add(10, 5));

Run it:

node app.js

Output:

15

In Node.js, a .mjs file is treated as ESM, while a .cjs file is treated as CommonJS. The "type" field in package.json also controls how .js files are interpreted within the relevant package scope.

For projects that use .js files consistently, setting "type": "module" is a common way to adopt ESM.

One practical detail: relative ESM imports in Node.js generally require the file extension.

For example:

import { add } from "./math.js";

This is the standard explicit form for native Node.js ESM.

Do not assume that a relative import such as ./math will resolve in exactly the same way as a CommonJS require("./math").

5. Can You Use Both require() and import in the Same Project?

Yes. A project can contain both CommonJS and ESM files.

However, you should understand the module boundaries rather than mixing syntax randomly.

For example, Node.js allows you to use .cjs for CommonJS and .mjs for ESM:

my-app/
├── package.json
├── app.mjs
└── legacy.cjs

The legacy.cjs file can use CommonJS syntax:

// legacy.cjs

module.exports = {
  message: "Hello from CommonJS",
};

The ESM file can load it:

// app.mjs

import legacy from "./legacy.cjs";

console.log(legacy.message);

Output:

Hello from CommonJS

Node.js supports importing CommonJS modules from ESM. In this example, the CommonJS module's module.exports value is available as the default import.

However, interoperability has some limitations, especially when importing named exports from CommonJS. Node.js may detect certain named exports, but this behavior should not be treated as identical to native ESM named exports in every situation.

The reverse direction also requires care.

A CommonJS file can use dynamic import() to load an ESM module:

// app.cjs

async function main() {
  const math = await import("./math.mjs");

  console.log(math.add(10, 5));
}

main();

This is useful when you need to work with an ESM-only package from a CommonJS project.

Because import() returns a promise, you need to handle it asynchronously.

The main lesson is simple: CommonJS and ESM can work together, but they are not interchangeable in every context.

6. What Is the Difference Between Static import and Dynamic import()?

It is important not to confuse these two forms.

Static import:

import { add } from "./math.js";

Dynamic import:

const math = await import("./math.js");

console.log(math.add(10, 5));

Static imports are declared at the top level and are resolved as part of the module loading process. They make dependencies explicit and help tools analyze the module graph.

Dynamic imports return a promise and allow you to load a module when it is needed.

For example, imagine your application has an optional report-generation feature that users rarely open.

Instead of loading the report module immediately, you could load it only when the user requests a report:

async function generateReport() {
  const reportModule = await import("./report.js");

  return reportModule.generateReport();
}

This pattern is useful when a module is optional or expensive to load.

In frontend applications, dynamic imports are also commonly used for code splitting, although the exact behavior depends on your bundler and framework.

In Node.js, dynamic imports are particularly useful for conditional loading and interoperability between module systems.

7. Is import Faster Than require()?

There is no universal rule that import is always faster than require().

Performance depends on several factors, including:

  • The number and size of dependencies.

  • How modules are structured.

  • Whether modules are loaded during startup or on demand.

  • Whether a bundler optimizes the application.

  • How much work happens during module initialization.

ESM has a more static module structure, which makes it easier for build tools to analyze imports and exports. This can support optimizations such as tree-shaking, where unused exports can be removed from a bundled application when the tool can safely prove they are unnecessary.

CommonJS can also be optimized in some situations, but its dynamic loading behavior can make static analysis more difficult.

For example:

import { add } from "./math.js";

A bundler can often determine that the application uses the add export and does not need the subtract export.

However, tree-shaking is not guaranteed simply because you use ESM. It depends on the bundler, package configuration, side effects, and how the code is written.

For ordinary Node.js backend applications, choosing ESM purely because you expect it to run faster is usually not the best decision.

Choose the module system that fits your project, dependencies, and tooling. If performance is a concern, measure startup time and runtime behavior rather than assuming one syntax is faster.

8. Common Errors When Switching From require() to import

Let's look at a few errors you might encounter while migrating a Node.js project.

Error 1: require is not defined

Suppose you have this code:

const fs = require("node:fs");

But your package.json contains:

{
  "type": "module"
}

Your .js file is now interpreted as ESM, where the CommonJS require function is not available by default.

Use an ESM import instead:

import fs from "node:fs";

If you need to use require() in a particular file, you can change its extension to .cjs, or use Node.js's createRequire() API where appropriate.

Error 2: Cannot use import statement outside a module

This error often appears when Node.js interprets a file as CommonJS even though it contains ESM syntax.

For example:

import fs from "node:fs";

To fix the issue, make sure the file is treated as ESM.

You can use .mjs:

app.mjs

Or add "type": "module" to the relevant package.json:

{
  "type": "module"
}

The correct solution depends on your project's structure and whether you want to migrate the whole package or only selected files.

Error 3: Missing File Extension

In native Node.js ESM, this relative import may fail:

import { add } from "./math";

Use the explicit file extension:

import { add } from "./math.js";

Bundlers and other JavaScript environments may resolve extensions differently, so do not assume that behavior in a frontend project always matches native Node.js.

Error 4: Mixing module.exports and export

Consider this file:

export function add(a, b) {
  return a + b;
}

module.exports = { add };

This mixes ESM and CommonJS export syntax in a way that does not work as intended in a native ESM module.

Choose one module system for that file.

For ESM:

export function add(a, b) {
  return a + b;
}

For CommonJS:

function add(a, b) {
  return a + b;
}

module.exports = { add };

Keeping module syntax consistent makes your code easier to maintain.

9. Which One Should You Use in a New Node.js Project?

If you are starting a new Node.js project, ESM is a good choice, particularly if your dependencies and tools support it well.

It uses the standard JavaScript module syntax and works naturally with modern JavaScript tooling.

For example:

import express from "express";

const app = express();

app.get("/", (req, res) => {
  res.send("Hello from Node.js");
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

This is a typical ESM-style Express application, assuming your project is configured for ESM and your installed Express version supports the import style shown.

However, if you are maintaining an existing application that already uses CommonJS, there may be no immediate reason to rewrite everything.

For an established project, consider:

  • Whether your dependencies support ESM.

  • Whether your testing tools and scripts work with ESM.

  • Whether your build and deployment configuration needs changes.

  • Whether migrating modules provides a practical benefit.

  • Whether you can migrate incrementally without introducing unnecessary risk.

You can continue using CommonJS in a compatible project. You do not need to convert every older Node.js application just because ESM is available.

For a new application, choose a module system deliberately and use it consistently.

Final Thoughts

Both require() and import help you organize JavaScript code into reusable modules, but they belong to different module systems.

require() is part of CommonJS and loads modules synchronously. It works naturally with module.exports and exports.

import belongs to ECMAScript Modules and works with named and default exports. Static imports are declared at the module level, while dynamic import() allows you to load modules on demand.

For modern JavaScript development, ESM is an excellent default when your Node.js environment, dependencies, and tooling support it. However, CommonJS remains useful for existing projects and some specific compatibility scenarios.

As a Node.js developer, you should be comfortable reading both styles. You will likely encounter CommonJS in older codebases and ESM in newer applications.

Once you understand how each module system works, debugging import errors, integrating dependencies, and structuring your applications becomes much easier.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘