মূল কন্টেন্টে যান
eLearner.app
মডিউল 8 · 1-এর পাঠ 4কোর্সে 29/32~12 min
মডিউল পাঠ (1/4)

ESM মডিউল: আমদানি/রপ্তানি

When a program grows, keeping everything in a single file becomes awkward. Modern JavaScript solves the problem with ES modules (ESM): each file is a module that can export functions, constants, classes, and other files can import them.

export

You export what you want to make public. Two forms:

JS
// somma.js
export function somma(a, b) {
  return a + b;
}

export const PI = 3.14159;

Or, at the end of the file:

JS
function somma(a, b) {
  return a + b;
}
const PI = 3.14159;
export { somma, PI };

import

From another file:

JS
// app.js
import { somma, PI } from './somma.js';

console.log(somma(1, 2)); // 3
console.log(PI); // 3.14159

The object { somma, PI } is the list of names you want to import. They must match the exported names.

Default export

Each module can have one "main" export, without a name:

JS
// log.js
export default function log(msg) {
  console.log('[app]', msg);
}

You import it by choosing the name locally:

JS
import log from './log.js';
log('ciao');

Renaming

JS
import { somma as plus } from './somma.js';
export { somma as add } from './somma.js'; // re-export

One "namespace" per file

Modules are isolated: a variable declared in a file does not end up in the global scope. You have to export it explicitly to make it visible elsewhere. This is a huge improvement over old-school JS where every <script> shared window.

Try it

In the exercises below you will not write real import/export syntax — the sandbox is a single file. Instead, we will ask you to organize the code into small separate functions that collaborate, as you would if each were in a different file.

ব্যায়াম#js.m8.l1.e1
প্রচেষ্টা: 0লোড হচ্ছে...

Define two separate functions: `square(n)` (returns n*n) and `sumOfSquares(a, b)` that uses square. Think of square as 'exported' from a file and reused by sumOfSquares.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

sumOfSquares(a,b) = square(a) + square(b)

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

Review exercise

ব্যায়াম#js.m8.l1.e2
প্রচেষ্টা: 0লোড হচ্ছে...

Define `isEven(n)` (true if n is even) and `countEven(arr)` that uses isEven to count even elements in an array. Keep them as two separate functions.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

arr.filter(isEven).length

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ