Working with ECMAScript Modules
- Introduced in ECMAScript 6 (ES6/ES2015), ECMAScript Modules (ESM) are a standardized module system for structuring and organizing code.
- They allow developers to divide their code into smaller, reusable pieces.
- Modularity: Split code into smaller, manageable files.
- Reusability: Share code between files or projects.
- Scope: Variables are scoped to the module by default, reducing global namespace pollution.
- Native Support: Works in modern browsers and Node.js (with some setup).
- File-based: Each module is a single
.jsfile. - Exporting: Define what parts of a module (variables, functions, classes, etc.) you want to make available to other files.
- Importing: Bring exported items from one module into another.
- Static Structure: Imports and exports are resolved at load time (not dynamically at runtime).
Named exports allow you to export multiple things from a module. The exported items can be functions, variables, or constants.
// math.jsexport const calculateSum = (a, b) => a + b;export const calculateDifference = (a, b) => a - b;
// You can also export multiple items in one lineconst calculateProduct = (a, b) => a * b;const calculateQuotient = (a, b) => a / b;export { calculateProduct, calculateQuotient };A default export is used when you want to export a single entity from the module, such as a function or a class.
// greet.jsexport default function greet(name) { return `Hello, ${name}!`;}You can also combine named and default exports in the same module.
// utils.jsexport const multiply = (a, b) => a * b;export default function divide(a, b) { return a / b;}There are various ways to import modules depending on how they are exported.
When importing named exports, you use curly braces {} to reference specific values from the module.
// main.jsimport { calculateSum, calculateDifference } from './math.js';
console.log(calculateSum(5, 3)); // 8console.log(calculateDifference(5, 3)); // 2When importing a default export, you can give the imported value any name you choose.
// main.jsimport greet from './greet.js';
console.log(greet('Alice')); // Hello, Alice!If you want to import everything from a module, you can use the * syntax and assign it to a single object.
// main.jsimport * as MathUtils from './math.js';
console.log(MathUtils.calculateSum(10, 5)); // 15- Rename on export:
const computeTotal = (a, b) => a + b;export { computeTotal as calculateSum };javascript
- Rename on import:
import { calculateSum as addNumbers } from './math.js';console.log(addNumbers(2, 3)); // 5javascript
In modern browsers, ECMAScript modules can be used by specifying the type="module" attribute in a <script> tag. This tells the browser to treat the script as an ESM.
<!-- index.html --><script src="main.js" type="module"></script>With this setup, the main.js file can import other modules, such as:
// main.jsimport { add } from './math.js';
console.log(add(2, 3)); // 5