Named Export & Default Export - JavaScript

ยท

1 min read

Named Export & Default Export - JavaScript

Exporting and importing is one of the features that ES6 provides. In Javascript, export is used to export values whether it's a function or a variable, or other so that we can use them in other JavaScript modules.

There are two ways to export: Named Export and Default Export.

Named Export

We can have multiple named exports in a module. Here, the exported value name must be the same as the imported value.

// named_export.js
let str = "named export";
export str;
// multiple exports
export let function_1 = () => {...}
// or export all at once
export { str, function_1 }
//named_import.js
import { str, function_1 } from ./named_export;
// or import all the named exports
import *  from ./named_export;

Default Export

A module can't have multiple default exports. Add default after export to make it a default export. We can import the default exports by any name. It doesn't have to be the same as the exported value.

// default_export.js
let str = "default export";
export default str;
// or
export { str as default };
//default_import.js
import str from ./default_export;
// call it by whatever name you want
import str_value from ./default_export;
ย