Splitting Code Into Parts
As a project grows, keeping everything in one file becomes unmanageable. ES Modules let you split your code into logical, reusable pieces.
export — Share Your Code
// math.js
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
export const PI = 3.14159;
// Export everything at once:
export { add, multiply, PI };
import — Use Others' Code
// main.js
import { add, PI } from './math.js';
console.log(add(2, 3)); // 5
console.log(PI); // 3.14159
// Import everything under a namespace:
import * as Math from './math.js';
console.log(Math.multiply(4, 5)); // 20
Using Modules in the Browser
<script type="module" src="main.js"></script>
Important
Modules always run in strict mode (use strict) automatically — even without writing it.
Caution
To use modules directly in the browser, the <script> tag MUST have the attribute type="module". Without it, the browser won't understand import/export.