Explain the differences between CommonJS modules and ES modules in JavaScript

Answer

1. Introduction

CommonJS and ES Modules are two different module systems in JavaScript used for organizing and sharing code between files.

2. Syntax Differences

Importing Modules

const fs = require('fs'); // Import a module
const customModule = require('./customModule'); // Import a local file
import fs from 'fs'; // Import a module
import customModule from './customModule.js'; // Import a local file

Exporting Modules

// Single export
module.exports = function () {
  console.log('Exported function');
};

// Multiple exports
exports.func1 = function () {
  console.log('Function 1');
};
exports.func2 = function () {
  console.log('Function 2');
};
// Single export
export default function () {
  console.log('Exported function');
}

// Multiple exports
export function func1() {
  console.log('Function 1');
}
export function func2() {
  console.log('Function 2');
}

3. Execution Model

4. Scope and Behavior

Skopiuj kod
if (someCondition) {
const moduleA = require('./moduleA');
}
// This will throw an error:
if (someCondition) {
  import './moduleA.js';
}

5. Default Exports vs Named Exports

6. File Extensions

7. Compatibility

8. Interoperability Between CJS and ESM

import fs from 'fs'; // Default behavior
const path = require('path'); // Using CommonJS in an ESM file
const { readFile } = await import('fs'); // Dynamic import required

9. Use Cases

Conclusion

MDN Web Docs: Import/Export

Node.js Documentation: CommonJS Modules

Node.js Documentation: ECMAScript Modules