es6

Chapter 11: Mastering ES6 Modules – Import, Export, and Default Bindings

Chapter 11: ES6 Modules – Import, Export, and Default Binding

Modules were introduced in JavaScript (ES6) in 2015 to help developers split code into reusable files. A module is simply a separate JavaScript file that runs in strict mode and does not pollute the global scope. This is essential for maintaining clean, maintainable, and scalable code — especially in frameworks like React and Angular.

📦 Exporting from a Module

Use the export keyword to expose variables, functions, or classes:


// message.js
export let message = 'ES6 Learning';

export function getMessage() {
  return message;
}

export class Logger {
  log(msg) {
    console.log('Log:', msg);
  }
}
  

Note: You must name what you export — anonymous exports like export function() {} are not allowed for named exports.

📥 Importing Bindings


import { message, getMessage } from './message.js';

console.log(message);       // ES6 Learning
console.log(getMessage());  // ES6 Learning
  

If you try to reassign an imported binding directly, it will throw an error:


// ❌ Invalid
message = 'Hello'; // Error
  

🧪 Example: Using setter to modify module state


// message.js
export let message = 'Hello ES6';
export function setMessage(msgInput) {
  message = msgInput;
}

// app.js
import { message, setMessage } from './message.js';

console.log(message); // Hello ES6
setMessage('I am learning ES6');
console.log(message); // I am learning ES6
  

📚 Importing Multiple Bindings


// callMe.js
export let a = 20, b = 10, val = 0;

export function sum() {
  val = a + b;
  return val;
}

export function multiply() {
  val = a * b;
  return val;
}

// app.js
import { a, b, val, sum, multiply } from './callMe.js';

sum();      
console.log(val);      // 30
multiply();
console.log(val);      // 200
  

🧱 Import All as Module Object


import * as cal from './callMe.js';

console.log(cal.a);           // 20
console.log(cal.multiply()); // 200
  

Note: Avoid importing everything unless you absolutely need all exports.

📝 Aliasing (Renaming Exports or Imports)

Export with alias:


// math.js
function add(a, b) {
  return a + b;
}
export { add as sum };
  

Import with alias:


import { sum as total } from './math.js';

console.log(total(5, 6)); // 11
  

✅ Default Exports

Each module can have only one default export.


// sort.js
export default function sort(arr) {
  return arr.sort();
}
  

Importing a default export:


import sort from './sort.js';

console.log(sort([3, 1, 2])); // [1, 2, 3]
  

🧩 Combining Default and Named Exports


// sort.js
export default function(arr) {
  return arr.sort();
}

export function heapSort(arr) {
  // some sorting logic
}
  

// Import both
import sort, { heapSort } from './sort.js';
  

Renaming Default Export:


import { default as quicksort, heapSort } from './sort.js';
  

📝 Comparison Table: Named vs Default Exports

Named Exports Default Export
Can export multiple values Only one default per module
Must use exact names when importing Can use any name during import
Import uses {} No braces required

📘 Assignments: Practice with ES6 Modules

  1. Create a math.js file that exports add() and subtract() functions. Import and use them in app.js.
  2. Create a module that exports a default class User and a named function getUserInfo. Import both properly.
  3. Use import * as utils to access all exports from a utilities file and call two different functions.
  4. Practice renaming an exported function using as during both export and import.
  5. Import both a default export and a named export from a single file and call both.

📌 Summary

  • Modules keep code clean, organized, and maintainable.
  • Named exports allow multiple exports, must be imported by name.
  • Default exports allow only one per file, imported without braces.
  • import * as module gathers all bindings into one object.
  • Use as to rename exports or imports.

Leave a Reply

Your email address will not be published. Required fields are marked *