Understanding Import and Export in JavaScript - Two Ways
JavaScript Components: What's the difference between "named exports" and "default exports"?
When you're working with larger JavaScript applications, like those built with React, you'll often break your code into different files or modules. Understanding how to import and export these parts is crucial. Let's explore two main methods to do this: named exports and default exports.
Named Exports
Named exports allow you to export multiple values from a file and import them using their specific names.
Exporting
In your module (Heading.jsx), you simply use the export
keyword before the item you want to export:
export function Heading() {
return <h1>My Favorite Foods</h1>;
}
Importing
When you want to use the exported item in another file, you import it using its specific name inside curly braces:
import { Heading } from "./Heading.jsx";
You must use the exact name of the exported item, ensuring clear understanding of what's being imported.
Default Exports
A default export is used when you have one main item to export from a file.
Exporting
You create a default export using the export default
keywords: (Heading.jsx)
function Heading() {
return <h1>My Favorite Foods</h1>;
}
export default Heading;
Importing
To import a default export, you don't use curly braces, and you can give it any name you like (though using the original name is conventional):
When to Use Which?
Named Exports: Choose this method if you have several items to export from a module and want to be explicit about what you're using.
Default Exports: Opt for this method when you have a single main item to export, making the code slightly more concise.
Conclusion
The choice between named and default exports is often based on style, project conventions, or specific needs. Understanding both methods equips you with the flexibility to structure your code in a way that suits your project.
As you grow in your programming journey, experimenting with both methods will help you get a feel for when to use each one, allowing you to write more organized and maintainable code.
I hope this will help you to understand, how to export and import components in JavaScript.
... Remember, when you feel you do not understand something, you are actually learning something. When your head is about to explode, sleep on it.
Lukas