Modules
Modules are a way to organize and structure code in a more modular and maintainable way. JavaScript modules allow you to split your code into multiple files and then import/export functionality between them.
ES6 Modules (ESM)
The ES6 module system was introduced in ECMAScript 2015 (ES6) and is used for handling modules in modern JavaScript. It uses import and export keywords to facilitate the sharing of code between different files.
Key Features of ES6 Modules (ESM)
- Static Structure: The import/export statements are resolved statically, meaning they are evaluated before code execution, which allows for better optimizations (e.g., tree-shaking).
- Default and Named Exports: You can have both default and named exports in a module.
CommonJS Modules (CJS)
CommonJS is the module system used by Node.js before ES6 was introduced. It is based on require and module.exports for importing and exporting code between different files.
Key Features of CommonJS
- Dynamic Structure:
require()is executed at runtime, so it supports conditional loading of modules and circular dependencies. - Synchronous: It loads modules synchronously, making it suitable for server-side code but less efficient for the browser.