Named exports are a way to export multiple values from a module in JavaScript, allowing for more organized and maintainable code. When using named exports, you can export variables, functions, or classes by their names, making it clear what is being imported in other modules. This feature is particularly useful in larger applications where modularity and clarity are essential.
In contrast to default exports, which allow only one export per module, named exports can include multiple items. This flexibility enables developers to share various functionalities from a single module without confusion.
To create a named export, you can use the following syntax:
export const myVariable = 'Hello, World!';
export function myFunction() {
console.log('This is a named export function');
}
In the example above, we are exporting a constant and a function. Both can be imported in another module using their respective names.
To import named exports, you can use the following syntax:
import { myVariable, myFunction } from './myModule';
console.log(myVariable); // Output: Hello, World!
myFunction(); // Output: This is a named export function
// mathUtils.js
export const PI = 3.14;
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
In the above example, we have a module called mathUtils.js that exports a constant PI and two functions, add and subtract. These can be imported in another file as follows:
import { PI, add, subtract } from './mathUtils';
console.log(PI); // Output: 3.14
console.log(add(2, 3)); // Output: 5
console.log(subtract(5, 2)); // Output: 3
In conclusion, named exports provide a robust way to manage multiple exports from a module, enhancing code clarity and maintainability. By following best practices and avoiding common pitfalls, developers can effectively utilize named exports in their projects.