Lecture Notes Of Day 21
Module System in JavaScript
Objective:
By the end of this session,
students will be able to organize JavaScript code into separate, reusable
modules. They will understand how to use the export and import keywords, and
the differences between default and named exports. They will also learn how to
apply modules in modern web development.
Introduction
to JavaScript Modules
A module is a piece of
code that is independent and reusable. Organizing code into modules is a
fundamental aspect of modern JavaScript development. Modules allow you to split
your code into smaller, manageable pieces. This not only makes your code easier
to maintain but also helps with better organization, debugging, and reuse.
JavaScript's module system allows
developers to export code (such as variables, functions, or classes)
from one module, and import it into another module, making it accessible
in different parts of your program.
1. The
export and import Keywords
The export keyword allows
you to expose parts of your code (functions, variables, or objects) so that
they can be used in other files. The import keyword is used to bring
those exported items into a different file where you need to use them.
1.1.
Using export
There are two types of exports in
JavaScript: named exports and default exports.
1.1.1.
Named Exports
Named exports allow you to export
multiple items from a module. You need to use the exact name when importing
them.
Example of Named Exports:
// file: math.js
// Exporting multiple items from math.js
export
const add = (a, b) => a + b;
export
const subtract = (a, b) => a - b;
In the above example, add and
subtract are both exported as named exports. To import them in another file,
you use their exact names.
// file: app.js
// Importing the named exports from math.js
import {
add, subtract } from './math.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(5,
3)); // Output: 2
Here, we import add and subtract
by using the same names as defined in math.js.
1.1.2.
Default Export
A default export is used
when you want to export a single value from a module. You can choose any name
for the default export, and it does not require curly braces when importing.
Example of Default Export:
// file:
math.js
// Default export
const
multiply = (a, b) => a * b;
export
default multiply;
In the above example, multiply is
the default export from the math.js module. To import it in another file, you
do not use curly braces and can name it anything you like.
// file: app.js
//
Importing the default export from math.js
import
multiplyFunction from './math.js';
console.log(multiplyFunction(5, 3)); // Output: 15
In this case, multiplyFunction is
an arbitrary name for the imported function, which is fine since it's the
default export.
2.
Default Exports vs Named Exports
|
Aspect |
Named
Exports |
Default
Export |
|
Number of Exports |
You can export multiple values
from a module |
You can export only one value
per module |
|
Syntax for Import |
import { item1, item2 } from
'file' |
import item from 'file' |
|
Flexibility |
Requires exact names for
imports |
Can be named anything during
import |
|
Usage |
When exporting several pieces
of code |
When exporting one main piece
of code |
- Named
exports are useful when you have multiple values to
export.
- Default
export is typically used when you are exporting a
single value, such as a function or a class.
3. Using
Modules in Modern Web Development
In modern web development, JavaScript
modules are heavily used in both client-side (browser) and server-side
(Node.js) applications. For client-side development, JavaScript modules are
usually loaded via <script type="module"> in HTML files, which
tells the browser to treat the script as a module.
3.1.
Using Modules in the Browser
To use modules in the browser,
you need to specify the type="module" attribute in the <script>
tag. This allows you to use import and export in the browser, making your code
modular and easier to manage.
Example:
<!--
index.html -->
<!DOCTYPE
html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>JavaScript Modules
Example</title>
</head>
<body>
<script type="module"
src="app.js"></script>
</body>
</html>
In the app.js file, you can
import and use any modules like this:
// app.js
import { add } from './math.js';
console.log(add(2,
3)); // Output: 5
3.2.
Using Modules in Node.js
In Node.js, modules are also an
essential part of development. However, before Node.js v14, you would use require()
to import modules. Starting from Node.js v14, you can also use import and
export for a more modern approach. You need to either set "type":
"module" in your package.json or use .mjs extensions for your
JavaScript files.
Example in Node.js:
//
package.json
{
"type": "module"
}
Then, you can use the import and
export syntax in your .js files.
4. Best
Practices in Using JavaScript Modules
- Use
meaningful names for your exports: Whether you're exporting a
function or a variable, make sure the names are clear and descriptive.
- Organize
code logically: Group related functions and variables into
separate files for better organization and readability.
- Use
default exports for main functionalities: For a single, main
function or object that the module is focused on, use the default export.
- Avoid
exporting everything: Only export what is necessary, keeping your
modules focused on specific tasks.
Conclusion
In this lesson, we covered how to
use the export and import keywords to modularize your JavaScript code. We
explored both named exports and default exports, and discussed
when to use each of them. You also learned how to use modules in both the
browser and Node.js environments.
Modules help make JavaScript code
more modular, reusable, and easier to maintain, which is a core principle in
modern web development.
Exercise:
1. Create a
module utils.js that contains two functions: one for adding and one for
subtracting numbers. Export both functions using named exports.
2. Create a main
JavaScript file, app.js, where you import the two functions and use them to
perform calculations and display the results in the console.
