ES6 Modules - Import and Export

Intermediate
110 XP
45 min
Lesson Content

ES6 Modules - Import and Export

Modules allow you to split your code into separate files, making it more organized and reusable. ES6 modules use import and export statements.

Exporting

// Named exports
// math.js
export const PI = 3.14159;
export function add(a, b) {
  return a + b;
}
export function subtract(a, b) {
  return a - b;
}

// Or export at the end
export { PI, add, subtract };

Default Export

// user.js
class User {
  constructor(name) {
    this.name = name;
  }
}

export default User;

Importing

// Named imports
import { add, subtract, PI } from './math.js';

// Import all as namespace
import * as math from './math.js';
math.add(1, 2);

// Default import
import User from './user.js';

// Rename imports
export { add as sum } from './math.js';
import { sum } from './math.js';

Combined Import/Export

// Re-export from another module
export { add, subtract } from './math.js';
export { default as User } from './user.js';
Example Code

Create and use ES6 modules

// Note: In a real environment, these would be separate files
// This demonstrates module concepts

// Simulating math.js module
export const PI = 3.14159;
export function add(a, b) {
  return a + b;
}
export function subtract(a, b) {
  return a - b;
}
export function multiply(a, b) {
  return a * b;
}

// Simulating user.js module
class User {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }
  
  getInfo() {
    return `${this.name} (${this.email})`;
  }
}

export default User;

// Simulating main.js (imports)
// In real code, you'd write:
// import { add, subtract, PI } from './math.js';
// import User from './user.js';

// For this example, we'll use the exports directly
console.log('PI:', PI);
console.log('Add:', add(5, 3));
console.log('Subtract:', subtract(10, 4));

const user = new User('John', 'john@example.com');
console.log('User:', user.getInfo());

Expected Output:

PI: 3.14159
Add: 8
Subtract: 6
User: John (john@example.com)
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code