JavaScript Modules
What are Modules?
Modules allow you to break up code into separate files.
Modules are chunks of self-contained code.
You use import and export to interchange functionalities between JavaScript modules.
How to Use Modules
Modules are imported from external files with the import statement.
Modules also rely on type="module" in the <script> tag.
Note
Modules operate in strict mode by default.
Modules must be stored on a server.
Export
To share code with other files, you use the export keyword.
A module can have multiple named exports and, optionally, one default export.
Named Exports
Let us create a file named person.js, and
fill it with the things we want to export.
You can create named exports two ways. In-line individually, or all at once at the bottom.
In-line individually:
person.js
export const name = "Jesse";
export const age = 40;
All at once at the bottom:
person.js
const name = "Jesse";
const age = 40;
export {name, age};
Default Exports
Let us create another file, named message.js, and
use it for demonstrating default export.
You can only have one default export in a file.
Example
message.js
const message = () => {
const name = "Jesse";
const age = 40;
return name + ' is ' + age + 'years old.';
};
export default message;
Import
You can import modules into a file in two ways, based on if they are named exports or default exports.
Named exports are constructed using curly braces. Default exports are not.
Import Named Exports
You must use the exact names of the exported variables or functions, enclosed in curly braces:
Example
Import named exports from the file person.js:
import { name, age } from "./person.js";
Import Default Exports
You can give a default export any name you like, during import, without using curly braces:
Example
Import a default export from the file message.js:
import message from "./message.js";
Importing Everything
You can import all named exports from a module as a single object using the * syntax.
// Import all named exports from utilities.js
import * as utils from "./utilities.js";
Benefits of Using Modules
Modules help structuring a codebase logically by separating concerns. This is essential for larger projects.
Modules prevent naming conflicts by keeping variables and functions within the module scope.
A module can be easily reused across different parts of an application and even in entirely new projects.
Small files are easier to maintain and debug, as you only need to focus on one piece of functionality.
Modules make explicit dependencies and are automatically loaded, reducing the risk of missing code.
Note
Modules only work with the HTTP(s) protocol.
A web-page opened via the file:// protocol cannot use import / export.