JavaScript modules are a key feature of ES6 that allow you to split your code into multiple files, making it more organised and easier to maintain. React takes advantage of these modules to keep components modular and reusable.
Modules rely on two primary keywords: export and import.
Export #
The export
keyword allows you to share variables, functions, or classes from one file so they can be used in other files. There are two main types of exports: Named Exports and Default Exports.
Named Exports #
With named exports, you can export multiple items from a file. These can be exported in two ways:
- Individually during their declaration.
- All together at the end of the file.
Example: In-line Individual Named Exports
person.js
export const name = "Alex";
export const age = 30;
Example: Export All at Once
person.js
const name = "Alex";
const age = 30;
export { name, age };
Default Exports #
A default export allows you to export a single value from a file. You can only have one default export per file.
Example: Default Export
message.js
const message = () => {
const name = "Alex";
const age = 30;
return `${name} is ${age} years old.`;
};
export default message;
Import #
The import
statement is used to bring in exported modules from other files. The way you import depends on whether the module was exported as a named export or a default export.
Importing Named Exports #
Named exports must be destructured using curly braces.
Example: Import Named Exports
main.js
import { name, age } from "./person.js";
console.log(name); // Alex
console.log(age); // 30
Importing Default Exports #
Default exports do not require destructuring and can be imported with any name.
Example: Import Default Export
main.js
import message from "./message.js";
console.log(message()); // Alex is 30 years old.
Key Benefits of Using Modules #
- Code Organisation: Makes it easier to split code into manageable chunks.
- Reusability: Encourages modular and reusable code by allowing sharing across files.
- Maintainability: Simplifies debugging and understanding by keeping functionality separated.
Summary #
React ES6 modules, with their export and import mechanisms, are essential for writing clean, modular code. By using named and default exports strategically, you can structure your applications for scalability and clarity.
Want to learn React with an instructor, either offline or online? Find experienced tutors near you and join Coaching Wallah—completely free for students!
Leave your comment