In ECMAScript 6 (ES6) JavaScript modules, you can export values from a module using two main approaches: named exports and default exports. These approaches allow you to organize and share code across different files in a more modular and maintainable way. Let’s explore each of these concepts in more detail:
- Named Exports:
Named exports allow you to export multiple values from a module and give each of them a specific name. You can import these values by using their respective names when importing in another module.
Example:
// moduleA.js
export const foo = 'Foo';
export function bar() {
// function implementation
}// moduleB.js
import { foo, bar } from './moduleA';
In this example, you export both the foo
constant and the bar
function from moduleA
, and you import them using their respective names in moduleB
.
2. Default Export:
Default export is used to export a single value as the default value for a module. This value can be a variable, function, class, or any other JavaScript entity. When importing a default export, you can assign it any name you want in the importing module.
Example:
// moduleC.js
const myDefault = 'Default Value';
export default myDefault;// moduleD.js
import myAlias from './moduleC';
In this example, the myDefault
value is exported as the default export from moduleC
. When importing it into moduleD
, it's assigned the name myAlias
.
It’s important to note that you can mix both named and default exports in the same module:
// moduleE.js
export const namedExport = 'Named Export';
const defaultExport = 'Default Export';
export default defaultExport;
When importing mixed exports, you can choose how to import them:
import myDefault, { namedExport } from './moduleE';
Here, myDefault
will receive the default export value, and namedExport
will receive the named export value.
In summary, named exports are useful when you want to export multiple values and import them with their specific names, while default exports are handy for exporting a single value and giving it a custom name when importing. The choice between the two depends on the structure and requirements of your codebase.
Thanks for reading 🙂