What are ES6 Modules?
ES6 Modules provide a way to split code into separate files and share functionality between them. Each module has its own scope, which helps prevent naming conflicts and makes code more maintainable.
💡 Key insight
Modules are like building blocks. Each file is a module that can export parts of its code and import from other modules.
Exporting from a Module
Named Exports
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const PI = 3.14159;
Default Export
// person.js
export default class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}`;
}
}
Importing into a Module
// Named imports
import { add, subtract, PI } from './math.js';
// Import with alias
import { add as sum } from './math.js';
// Import all as a namespace
import * as math from './math.js';
// Default import
import Person from './person.js';
// Mix default and named
import Person, { add } from './person.js';
Module Script Tag
To use modules in HTML, use the type="module" attribute.
<script type="module">
import { add } from './math.js';
console.log(add(2, 3));
</script>
Common Mistakes
- Forgetting
type="module"in script tags - Using relative paths incorrectly (
./and../) - Mixing default and named exports incorrectly
- Using
importin non-module scripts
Quick Quiz
1. What is the purpose of ES6 modules?
2. Which keyword is used to export a function from a module?
3. How do you import everything from a module as an object?
Summary
- ES6 modules organize code into separate files
- Use
exportto make code available - Use
importto bring code into another module - Named exports:
export const name = value - Default export:
export default - Add
type="module"to script tags
