Performance: CommonJS vs ESM differences
This affects module loading speed and runtime execution efficiency in Node.js applications.
Jump into concepts and practice - no test required
import fs from 'fs'; import path from 'path'; // ESM loads modules asynchronously and supports static analysis
const fs = require('fs'); const path = require('path'); // multiple require calls synchronously load modules
| Pattern | Module Loading | Blocking | Bundle Size | Verdict |
|---|---|---|---|---|
| CommonJS require() | Synchronous | Blocks event loop | Includes all code | [X] Bad |
| ESM import | Asynchronous | Non-blocking | Supports tree shaking | [OK] Good |
require function to import modules.export default to export a default function or value.module.exports = function() {} and C are CommonJS exports; D is invalid syntax.const message = require('./message');
console.log(message);
And the file message.js contains:
module.exports = 'Hello from CommonJS';
const fs = require('fs');require which is CommonJS syntax, but in ESM modules, require is not available.import statements; require is undefined.module.exports and add a separate export default for ESM mixes syntaxes which doesn't work reliably, C requires dynamic import in consumers, D limits to ESM-only.