Why Do We Need Modules?
Imagine building a large application. If all your JavaScript codeβfunctions, variables, classesβis in one giant file or in multiple files that all share the same global scope, you'll run into problems:
- Naming Conflicts: You might accidentally use the same variable name in different parts of your application, causing bugs.
- Lack of Organization: It's hard to find the code you're looking for.
- Reusability: It's difficult to reuse a piece of code in a different project without copying and pasting.
Modules solve this. A module is simply a file. Variables and functions declared in a module are scoped to that module by default; they are not available globally. You can then explicitly choose what to export from a module to make it available, and what to import into another module.
The export Statement
There are two types of exports: named and default.
- Named Exports: You can have multiple named exports per module. They are great for exporting several utility functions or values.
- JavaScript (utils.js):
- JavaScript
// Exporting as they are declared
export const PI = 3.14159;
export function add(a, b) {
  return a + b;
}
// Or export them all at the end
const subtract = (a, b) => a - b;
export { subtract };
- Default Export: You can only have one default export per module. It's often used for the "main" thing the module provides, like a class or a primary function.
- JavaScript (User.js):
- JavaScript
export default class User {
  constructor(name) {
    this.name = name;
  }
  greet() {
    console.log(`Hello, ${this.name}`);
  }
}
The import Statement
To use the exported code, you import it into another module.
JavaScript (main.js):
JavaScript
// Importing named exports requires curly braces {}
// You can also rename them with 'as'
import { PI, add as sum } from './utils.js';
// Importing a default export doesn't use curly braces
// You can name it whatever you want
import Person from './User.js';
console.log(`The value of PI is ${PI}.`);
console.log(`The sum of 5 and 3 is ${sum(5, 3)}.`);
const user = new Person('Alice');
user.greet(); // "Hello, Alice"
Using Modules in the Browser
To tell the browser that your script is a module, you must add type="module" to your <script> tag in the HTML file.
HTML (index.html):
HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JS Modules</title>
</head>
<body>
    <h1>Check the console!</h1>
    <script type="module" src="main.js"></script>
</body>
</html>