JavaScript Modules (import/export)
JavaScript Modules allow you to split your code into separate files and import only what you need. This makes your code organized, reusable, and easier to maintain.
Why Use Modules?
- Organize code into logical files
- Avoid global variables and name collisions
- Reuse code across multiple files
- Load only the necessary parts of a module
1. Exporting from a Module
export keyword (named exports):
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
You can export multiple values using named exports.
export default (single default export):
// greet.js
export default function greet(name) {
return
`Hello, ${name}!`;
}
Only one export default is allowed per file.
2. Importing Modules
Import named exports:
// main.js
import { add, subtract } from './math.js';
console.log(add(3, 4)); // 7
console.log(subtract(10, 5)); // 5
Import default export:
// main.js
import greet from './greet.js';
console.log(greet("Alice")); // Hello, Alice!
Import everything as an object:
import * as math from './math.js';
console.log(math.add(2, 3)); // 5
console.log(math.subtract(6, 1)); // 5
Important Notes
- Modules must be in separate .js files
- Add type= "module" in HTML when using ES6 modules in browser:
<script type="module" src="main.js"></script>
- Always use relative paths (./module.js)
- Works natively in modern browsers and Node.js (v14+)
Example Project Structure
/project
├── main.js
├── math.js
└── greet.js