Curriculum / Advanced / Lesson 26

ES6 Modules

import/export, and organizing code in modules.

26 of 30
advanced πŸ“– 6 min read 🎯 3 questions

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

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

Back to curriculum