agyanadda@gmail.com

JS Modules

Modern JS and Best Practices 1 min read Updated Dec 1, 2026 Topic 37 of 38

Modules split code into separate files. Each file shares only what it exports.

Export

// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
export default function greet() { return 'Hi'; }

Import

// app.js
import greet, { area, PI } from './math.js';
  • Named exports are imported in { } with the same name
  • One default export per file, imported with any name

Use in HTML

<script type="module" src="app.js"></script>

Modules run in strict mode, are deferred automatically, and must be served from a web server (not opened as file://).

Example

Example — Export and import (two files) JavaScript
// ---- file: utils.js ----
export const GST = 18;
export function withGst(price) {
  return price + price * GST / 100;
}
export default function formatINR(n) {
  return '₹' + n.toLocaleString('en-IN');
}

// ---- file: app.js ----
import formatINR, { withGst, GST } from './utils.js';

console.log(`Price with ${GST}% GST:`, formatINR(withGst(1000)));

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

Modules need separate files and a web server, so this example is for reading, not for the Try it editor.

Test Yourself With Exercises

Exercise 1 Multiple Choice

How many default exports can a file have?

Exercise 2 True / False

Named imports are written inside curly braces.

Exercise 3 Fill in the Blank

To use modules in HTML, add type="___" to the script tag.

Frequently Asked Questions

Browsers block modules loaded from file://. Run a local server, such as VS Code Live Server or php -S localhost:8000.