
ES6 Modules are the standard way to organize and share code in modern JavaScript. They allow you to break up your code into smaller, reusable files and explicitly define what values are exported and imported between them.
Named Exports
You can export multiple values from a single file using the `export` keyword. When importing, you use curly braces to specify which values you want.
// ๐ lib.js
export const PI = 3.14;
export function add(a, b) {
return a + b;
}
// ๐ main.js
import { PI, add } from './lib.js';
console.log(add(5, 10) * PI);
Default Exports
A file can have only one default export. It's often used for the primary value being exported from the module, like a class or a main function.
// ๐ User.js
export default class User {
constructor(name) {
this.name = name;
}
}
// ๐ main.js
import MyUser from './User.js'; // You can name it anything
const user = new MyUser('Alice');
Using Modules in the Browser
To use ES6 modules in a browser, you must add `type="module"` to your script tag.
<script type="module" src="main.js"></script>
Comments
Post a Comment