Lesson 70 - Importing and Exporting Modules in JavaScript
JavaScript modules allow you to break your code into smaller, reusable files. They make your code more maintainable, organized, and scalable. In this lesson, you'll learn how to use the import
and export
statements to work with modules in JavaScript.
What Are JavaScript Modules?
A module is a separate JavaScript file that contains related code. Instead of having all your JavaScript logic in one large file, you can divide your project into multiple files and import only the parts you need.
Advantages of Using Modules
- Code Reusability: You can reuse functions, classes, and variables across different files.
- Encapsulation: Keeps code organized and prevents variable/function name conflicts.
- Easier Maintenance: Allows you to debug and update specific parts of your application without affecting the whole codebase.
Exporting from a Module
To use a function, variable, or class from another file, you must first export it.
Named Export
You can export multiple items from a module using named exports.
Example: Exporting multiple items (file: math.js
)
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
Default Export
Each module can have only one default export. It is useful when exporting a single function, class, or object.
Example: Default export (file: logger.js
)
export default function logMessage(message) {
console.log("Log:", message);
}
Importing Modules
To use the exported functions or variables, you need to import them.
Importing Named Exports
You must use curly braces {}
when importing named exports.
Example: Importing named exports (file: app.js
)
import { PI, add, subtract } from './math.js';
console.log(PI); // Output: 3.14159
console.log(add(5, 3)); // Output: 8
console.log(subtract(10, 4)); // Output: 6
Importing Default Exports
When importing a default export, you can name it anything.
Example: Importing default export (file: app.js
)
import logMessage from './logger.js';
logMessage("Hello, Modules!"); // Output: Log: Hello, Modules!
Importing Everything
You can import all exports from a module using *
and give it an alias.
Example: Importing everything (file: app.js
)
import * as MathUtils from './math.js';
console.log(MathUtils.PI); // Output: 3.14159
console.log(MathUtils.add(5, 3)); // Output: 8
Using Modules in the Browser
To use ES modules in an HTML file, set the type="module"
attribute in the <script>
tag.
Example: Including a module in an HTML file
<script type="module" src="app.js"></script>
???? Note: When using modules in the browser, you must serve your files from a local server. Using file://
URLs won't work.
Exercise
- Create a file
greetings.js
and export two functions:sayHello(name)
: Logs"Hello, <name>!"
sayGoodbye(name)
: Logs"Goodbye, <name>!"
- Create another file
main.js
and import the functions. - Call both functions with any name.
- Run the script using a module in an HTML file.