In JavaScript, exporting a module allows you to share code between different files, promoting modular programming and code reusability. There are two primary ways to export modules: named exports and default exports. Understanding how to use these methods effectively is crucial for any frontend developer.
Named exports allow you to export multiple variables, functions, or classes from a single module. You can import them using the same names in another module. Here’s how to do it:
// module.js
export const name = 'John Doe';
export function greet() {
return `Hello, ${name}!`;
}
In the above example, we export a constant and a function. To import these in another file, you would do the following:
// main.js
import { name, greet } from './module.js';
console.log(name); // Output: John Doe
console.log(greet()); // Output: Hello, John Doe!
Default exports are used when you want to export a single value or object from a module. This can be a function, class, or any other value. Here’s an example:
// module.js
const greet = () => {
return 'Hello, World!';
};
export default greet;
To import a default export, you can use any name you choose:
// main.js
import greetFunction from './module.js';
console.log(greetFunction()); // Output: Hello, World!
You can also combine named and default exports in a single module. This allows for flexibility in how you structure your exports:
// module.js
export const name = 'John Doe';
export function greet() {
return `Hello, ${name}!`;
}
const farewell = () => {
return 'Goodbye!';
};
export default farewell;
In this case, you can import both named and default exports:
// main.js
import farewellFunction, { name, greet } from './module.js';
console.log(name); // Output: John Doe
console.log(greet()); // Output: Hello, John Doe!
console.log(farewellFunction()); // Output: Goodbye!
By understanding and applying these export methods correctly, you can create a more organized and maintainable codebase.