Before ES6, JavaScript didn’t have a built-in way to split code into separate files. With ES6, the import and export keywords made it easy to organize code into modules.
Why Use Modules?
- Keep your code organized
- Split large codebases into smaller, manageable files
- Reuse code across multiple files
Exporting from a Module
Use export to make variables, functions, or classes available to other files.
Named Export
// file: mathUtils.js
export const PI = 3.14;
export function add(a, b) {
return a + b;
}
Default Export
// file: greet.js
export default function greet(name) {
return `Hello, ${name}`;
}
Importing a Module
Import Named Exports
// file: main.js
import { PI, add } from './mathUtils.js';
console.log(add(5, 10)); // 15
console.log(PI); // 3.14
Import Default Export
import greet from './greet.js';
console.log(greet('Alice')); // Hello, Alice
Import Everything
import * as MathUtils from './mathUtils.js';
console.log(MathUtils.add(1, 2)); // 3
console.log(MathUtils.PI); // 3.14
Important Notes
- You must use type=”module” in your HTML to load ES6 modules in the browser.
- Modules are loaded using strict mode by default.
- Modules are loaded asynchronously and cached.
<script type="module" src="main.js"></script>
Common Errors
- Uncaught SyntaxError: Make sure to use
.jsfile extension andtype="module". - CORS issues: You must run the code from a local server, not directly via the file system.
When to Use ES6 Modules
- Modern frontend projects (React, Vue, etc.)
- Reusable libraries and utilities
- Clean code separation for better collaboration
Conclusion
ES6 modules let you build better-organized and reusable JavaScript code. With import and export, your apps become easier to manage, test, and scale. Whether you’re building a small tool or a large app, modular JavaScript is the way forward.
Post a Comment