Using Node.js require vs. ES6 import/export

Better Stack Team
Updated on March 11, 2024

Node.js uses CommonJS-style require for module loading, while ES6 introduces a native import and export syntax. Each has its own style and use cases.

Using require (CommonJS):

 
// Importing a module using require
const fs = require('fs');
const path = require('path');

// Exporting from a module using module.exports
const myModule = require('./myModule');
module.exports = myModule;
  • Pros:
    • Widely used in Node.js and supported in many environments.
    • Dynamic loading allows conditionally loading modules.
  • Cons:
    • Synchronous by default, which can lead to slower startup times.
    • Requires additional tools like Babel for using ES6 features in older Node.js versions.

Using import and export (ES6 Modules):

 
// Importing a module using import
import fs from 'fs';
import path from 'path';

// Exporting from a module using export
import myModule from './myModule';
export default myModule;
  • Pros:
    • Standardized in ECMAScript 6 (ES2015) and later.
    • Supports static analysis for better tooling and optimizations.
    • Allows for named exports, which makes it clearer which parts of the module are being used.
  • Cons:
    • Not yet fully supported in all environments (though widely supported in modern Node.js versions).
    • Requires a file extension when importing (e.g., .js).
    • Does not support dynamic loading as require does.

Interoperability:

In many modern Node.js projects, you can use a mix of both require and import/export syntax, thanks to tools like Babel or the built-in ESM (ECMAScript Modules) support in recent Node.js versions. For example, you might use import for newer code and libraries, while still using require for older or third-party modules.

Migration:

If you are working in a Node.js environment that supports ESM (ECMAScript Modules), you can gradually migrate your codebase from require to import/export. Keep in mind that there might be differences in behavior, especially regarding the handling of circular dependencies and variable hoisting.

Ultimately, the choice between require and import/export depends on your project's requirements, the Node.js version you are targeting, and your personal or team preferences.