📦

How to Use ES6 Modules in JavaScript

JavaScriptIntermediate

Import and export code between files.

Code Example

JavaScript
// math.js - Exporting
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

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

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

console.log(PI); // 3.14159
console.log(add(5, 3)); // 8
console.log(subtract(10, 4)); // 6

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

// Rename imports
import { add as addition } from './math.js';
console.log(addition(2, 3));

// Import everything
import * as Math from './math.js';
console.log(Math.PI);
console.log(Math.add(1, 2));

// Dynamic imports
async function loadModule() {
  const module = await import('./math.js');
  console.log(module.add(10, 20));
}

loadModule();

// Re-exporting
// utils.js
export { add, subtract } from './math.js';
export { default as Calculator } from './math.js';

// Named exports
export const version = "1.0.0";
export function helper() {
  return "Helper function";
}

// Export list
const config = { debug: true };
const logger = { log: console.log };
export { config, logger };

Explanation

Use export to expose code, import to use it. default export for main functionality. Named exports for utilities. Dynamic import() for lazy loading.

Related Tutorials