JavaScript Modules
Modules allow you to break code into separate files and import/export values between them, improving code organization, maintainability, and reuse.
Key Topics
export and import
Use export
to expose variables, functions, or classes from a module, and import
them in another file.
Default Exports
Default exports allow one main value to be exported. Import it without braces.
Named Exports
Named exports allow multiple values to be exported. Import them using braces.
// math.js
export function add(a, b) { return a + b; }
// main.js
import { add } from './math.js';
console.log(add(2,3)); // 5
JavaScript Usage in DOM
Use modules to separate UI logic, helper functions, and configuration data. When using modules in the browser, include type="module"
in the script tag.
<script type="module" src="main.js"></script>
Key Takeaways
- Modularity: Separate code into maintainable parts.
- Export/Import: Share code between files.
- Default/Named Exports: Choose the best style for your API.
- DOM Integration: Modularize DOM-related code for better structure.