JavaScript Modules (ESM)

ES Modules let you split code into files and import only what you need. In browsers, use <script type="module">. Files must be served from the same origin or allowed by CORS.

1) Enable Modules in HTML

Use type="module" so the browser treats files as modules. Imports are deferred automatically.


<!-- index.html -->
<script type="module" src="./main.js"></script>

2) Named Exports & Imports

Export multiple things by name, import the ones you need with braces.


// math.js
export const PI = 3.14159;
export function add(a,b) { return a+b; }

// main.js
import { PI, add } from './math.js';
console.log(add(2,3), PI);

3) Default Export

Each module can optionally export one default value.


// greet.js
export default (name) => `Hello ${name}`;

// main.js
import greet from './greet.js';
console.log(greet('Sonu'));

4) Namespace Import

Import everything as an object when that’s convenient.


// main.js
import * as M from './math.js';
console.log(M.PI, M.add(1,2));

5) Re-export from a Barrel File

Collect exports from many files into one entry (handy for library structure).


// lib/index.js
export * from './math.js';
export { default as greet } from './greet.js';

// main.js
import { PI, add, greet } from './lib/index.js';

6) Module Scope & Strict Mode

Modules are always in strict mode and have their own scope (variables aren’t global unless you attach to window).


// main.js (module)
let secret = 123; // not global
// window.secret === undefined

7) Live Bindings (Exports Update)

Imports read the current value of exports (they’re references, not copies).


// counter.js
export let count = 0;
export function inc() { count++; }

// main.js
import { count, inc } from './counter.js';
inc(); console.log(count); // 1

8) Dynamic import()

Load a module at runtime (returns a promise). Useful for code-splitting or on-demand features.


document.getElementById('btn').addEventListener('click', async () => {
  const mod = await import('./math.js');
  alert(mod.add(2,3));
});

9) Importing JSON (Native)

Modern browsers allow JSON modules with an import assertion.


// data.json
{ "site": "codingwithsonu.com", "year": 2025 }

// main.js
import data from './data.json' assert { type: 'json' };
console.log(data.site);
Tip: Use type="module" scripts and always import with a path (e.g., './file.js'). For cross-origin files, ensure correct CORS headers or serve from your own domain.