Difference Between Require and Import in Node.js

This article explains the key differences between the require and import syntax in Node.js. It covers their underlying module systems, loading mechanisms, syntax rules, and performance implications to help you decide which one to use in your JavaScript projects.

CommonJS (require) vs. ES Modules (import)

The fundamental difference between require and import is that they belong to two distinct module systems:

1. Synchronous vs. Asynchronous Loading

2. Dynamic vs. Static Loading

3. Strict Mode

4. Syntax and Exporting Differences

The way modules are exported and imported differs significantly between the two systems.

CommonJS (require and module.exports)

To export in CommonJS:

// math.js
const add = (a, b) => a + b;
module.exports = { add };

To import in CommonJS:

const { add } = require('./math');

ES Modules (import and export)

To export in ES Modules:

// math.js
export const add = (a, b) => a + b;

To import in ES Modules:

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

5. File Extensions and Node.js Execution

Node.js handles these two systems differently based on your project configuration: