What is the difference between require and import?
`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.
// 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.
// 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';` |
| Loading | Synchronous | Asynchronous |
| Standard | Node.js specific | ECMAScript standard |
| Return Value | Returns a copy of the `module.exports` object | Returns live bindings to exported values |
| Top-level await | Not directly supported | Supported |
| File Extension | `.js` (default) | `.mjs` or `.js` with `"type": "module"` in `package.json` |
| Dynamic Import | Not natively (`import()` can be used but functions as ESM) | Native support (`import()`) |
| Browser Support | No native browser support | Native browser support |
| Bindings | Exports are copies of values at the time of export. | Exports are live bindings; changes in the original module are reflected. |