JavaScript modules enable you to divide your code into separate files, making it easier to manage and maintain. ES Modules utilize import
and export
statements to share code between files.
Exporting
You can export functions or variables from any file using two types of exports: Named and Default.
Named Exports
You can create named exports in two ways: in-line individually or all at once at the end of the file.
In-line Individually:
// person.js export const firstName = "Alice"; export const age = 30;
All at Once at the Bottom:
// person.js const firstName = "Alice"; const age = 30; export { firstName, age };
Default Exports
You can only have one default export in a file. Default exports are typically used to export a single function, class, or object.
// message.js const message = () => { const firstName = "Alice"; const age = 30; return `${firstName} is ${age} years old.`; }; export default message;
Importing
You can import modules into a file in two ways, depending on whether they are named exports or default exports.
Importing Named Exports
Named exports must be imported using curly braces.
import { firstName, age } from "./person.js";
Importing Default Exports
Default exports do not require curly braces.
import message from "./message.js";