Modules in JavaScript
import & export



Introduction to JavaScript Modules

Modules help in breaking a JavaScript codebase into reusable and manageable pieces. Before ES6, developers used patterns like IIFEs or libraries like RequireJS to emulate modularity. ES6 introduced native support for modules through export and import.

Why Use Modules?

Types of Exports

Using Named Exports

Let's create a file mathUtils.js and export multiple functions:

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

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

Now, import them into another file:

// app.js
import { add, subtract } from './mathUtils.js';

console.log(add(10, 5));
console.log(subtract(10, 5));

Output:

15
5

Using Default Exports

Suppose a module has only one primary export, you can use export default:

// logger.js
export default function log(message) {
  console.log('Log:', message);
}

Importing a default export does not require curly braces:

// app.js
import log from './logger.js';

log('Modules are awesome!');

Output:

Log: Modules are awesome!

Can You Combine Named and Default Exports?

Yes, a file can contain both:

// helpers.js
export default function greet(name) {
  return `Hello, ${name}`;
}

export const PI = 3.14;
// app.js
import greet, { PI } from './helpers.js';

console.log(greet('JavaScript'));
console.log(PI);

Output:

Hello, JavaScript
3.14

Running JavaScript Modules

If using in Node.js, ensure the file extension is .mjs or add "type": "module" to your package.json.

node app.mjs

If using in browser, use type="module" in your script tag (for completeness, but not needed here).

Common Questions

Can I rename an imported function?

Yes, using as keyword:

import { add as sum } from './mathUtils.js';
console.log(sum(2, 3));

Output:

5

Can I import everything?

Yes, using * as syntax:

import * as math from './mathUtils.js';

console.log(math.add(1, 2));
console.log(math.subtract(5, 3));

Output:

3
2

Summary

Mastering modules will help you write cleaner, modular, and maintainable code for large applications.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M