🟢 Node.js Q11 / 110

What is the difference between require and import?

AI-Powered Answer ✓ Answered

`require` and `import` are both used to include modules in Node.js applications, but they belong to different module systems: CommonJS and ES Modules (ESM), respectively. Understanding their distinctions is crucial for modern Node.js development.

CommonJS (`require`)

CommonJS is Node.js's original and default module system. It loads modules synchronously, meaning that when you require() a module, Node.js pauses execution until the module is fully loaded and processed. Exports are defined using module.exports or exports.

javascript
// myModule.js
const greet = (name) => `Hello, ${name}!`;
module.exports = { greet };

// app.js
const { greet } = require('./myModule');
console.log(greet('World')); // Output: Hello, World!

ES Modules (`import`/`export`)

ES Modules (ESM) are the official standard for modules in JavaScript. They load modules asynchronously, which is beneficial for performance, especially in browser environments and for future features like top-level await. Node.js supports ESM through the .mjs file extension or by setting "type": "module" in package.json.

javascript
// myModule.mjs or myModule.js (with "type": "module" in package.json)
export const greet = (name) => `Hello, ${name}!`;

// app.mjs or app.js (with "type": "module" in package.json)
import { greet } from './myModule.js';
console.log(greet('World')); // Output: Hello, World!

Key Differences Summary

Feature`require` (CommonJS)`import` (ES Modules)
Syntax`const m = require('module');` `const { f } = require('module');``import m from 'module';` `import { f } from 'module';`
LoadingSynchronousAsynchronous
StandardNode.js specificECMAScript standard
Return ValueReturns a copy of the `module.exports` objectReturns live bindings to exported values
Top-level awaitNot directly supportedSupported
File Extension`.js` (default)`.mjs` or `.js` with `"type": "module"` in `package.json`
Dynamic ImportNot natively (`import()` can be used but functions as ESM)Native support (`import()`)
Browser SupportNo native browser supportNative browser support
BindingsExports are copies of values at the time of export.Exports are live bindings; changes in the original module are reflected.