J

ES6 Modules

JavaScript syntax guide

Importing and exporting modules in JavaScript

ES6 Modules

Importing and exporting modules in JavaScript

JavaScript es6 modules (javascript)
        
          // Exporting (in math.js)
// Named exports
export const PI = 3.14159;
export function add(a, b) {
  return a + b;
}

// Default export
export default class Calculator {
  multiply(a, b) {
    return a * b;
  }
}

// Importing
import { PI, add } from './math.js';
import Calculator from './math.js';

// Or import everything
import * as MathUtils from './math.js';

// Usage
console.log(PI); // 3.14159
console.log(add(2, 3)); // 5

const calc = new Calculator();
console.log(calc.multiply(4, 5)); // 20

// Dynamic imports
const module = await import('./math.js');
console.log(module.PI);
        
      

Explanation

ES6 modules provide a standard way to organize and share code. Use named exports for multiple exports and default export for the main export.

Common Use Cases

  • Code organization
  • Reusability
  • Dependency management
  • Tree shaking

Related JavaScript Syntax

Master ES6 Modules in JavaScript

Understanding es6 modules is fundamental to writing clean and efficient JavaScript code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using es6 modules effectively in your JavaScript projects.

Key Takeaways

  • Code organization
  • Reusability
  • Dependency management