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.