![]() |
VOOZH | about |
Importing modules makes your code reusable. NodeJS offers two ways to do this: CommonJS (require()) and ES6 modules (import/export). Both achieve the same goal—sharing code, but use different syntax.
CommonJS is the older, traditional way. ES6 modules are newer and offer some advantages, but both are commonly used in NodeJS development.
Here's a comparison between NodeJS's require and ES6's import/export syntax:
| Feature | require (CommonJS) | import/export (ES6 Modules) |
|---|---|---|
| Module System | CommonJS | ES6 Modules |
| Syntax | const module = require('module'); | import module from 'module'; |
| Loading | Synchronous | Asynchronous |
| Dynamic Loading | Supported | Not natively supported (can use import() for dynamic imports) |
| Exports | Single object (module.exports) | Named exports and default exports |
| Usage Context | Primarily used in NodeJS | Supported in modern JavaScript environments, including browsers and NodeJS |
| File Extension | .js | .js or .mjs (depending on environment and configuration) |
| Hoisting | Non-lexical (stays where placed) | Lexical (hoisted to the top) |
| Support | Widely supported in NodeJS | Requires enabling ES6 modules in NodeJS (e.g., setting "type": "module" in package.json) |
In Node.js, require() and ES6 import/export each have their own use cases, so choose the one that best suits your requirements.
The require function is part of the CommonJS module system, which NodeJS uses to handle modules. It allows you to include external modules, JSON files, or local files in your application.
// Importing a built-in module
const fs = require('fs');
// Importing a local module
const myModule = require('./myModule');
// Exporting a function
module.exports = function() {
console.log('Hello from myModule!');
};While ES6 modules are gaining popularity, require() (CommonJS) is still widely used in NodeJS, especially in older projects and libraries. It's important to understand how it works.
ES6 introduced a standardized module system with import and export statements, offering a more declarative and flexible approach to module handling. This system supports both static and dynamic imports.
// Importing a built-in module
import fs from 'fs';
// Importing a local module
import { myFunction } from './myModule';
// Exporting a function
export function myFunction() {
console.log('Hello from myFunction!');
}ES6 modules (import/export) offer a modern and often preferred way to handle modules in JavaScript, including NodeJS. They bring several advantages.
Both require and import/export are used to load modules in NodeJS, but they differ in their module systems, loading mechanisms, and syntax. While require is synchronous and based on CommonJS, ES6 import/export offers asynchronous, statically-analyzable imports, making it more suitable for modern JavaScript development.