What is export default in JavaScript ?
The export statement is used when creating JavaScript modules to export objects, functions, and variables from the module so they can be used by other programs with the help of the import statements. There are two types of exports. One is Named Exports and the other is Default Exports.
Named Exports
Named exports are useful for exporting several values. During the import, it is mandatory to use the same name as the corresponding object.
Syntax:
// Exporting individual features
export let name1 = …, name2 = …, …, nameN; // also var, const
// Export list
export { name1, name2, …, nameN };
//Exporting everything at once
export { object, number, x, y, boolean, string }
// Renaming exports
export { variable1 as name1, variable2 as name2, …, nameN };
// export features declared earlier
export { myFunction, myVariable };
Example: In this example, we are exporting everything by their default name.
javascript
function square(x) {
return x * x;
}
function cube(x) {
return x * x * x;
}
export { square, cube };
import { square, cube } from './math;
console.log(square(8))
console.log(cube(8))
|
Output:
64
512
Default Exports
Default exports are useful to export only a single object, function, variable. During the import, we can use any name to import.
Example: In this example, we are exporting the variable by using “export default” keywords.
javascript
let x = 4;
export default x;
import y from './module' ;
console.log(y);
|
Output:
4
Using Named and Default Exports at the same time
It is possible to use Named and Default exports in the same file. It means both will be imported in the same file.
Example: In this example, we are exporting the function.
javascript
let x = 2;
const y = 4;
function fun() {
return "This a default export."
}
function square(x) {
return x * x;
}
export { fun as default , x, y, square };
|
While importing this module.js we can use any name for fun because it is a default export and curly braces for other named exports.
javascript
import anyname, { x, y, square} from './module.js' ;
console.log(anyname());
console.log(x);
|
Output:
This is a default export.
2
Last Updated :
13 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...