Named Export vs Default Export in ES6

Named Export vs Default Export in ES6

ES6 provides us to import a module and use it in other files. Strictly speaking in React terms, one can use stateless components in other components by exporting the components from their respective modules and using it in other files.

ES6 provides two ways to export a module from a file: named export and default export.

Named Export: (export)

With named exports, one can have multiple named exports per file. Then import the specific exports they want surrounded in braces. The name of imported module has to be the same as the name of the exported module.

// imports// ex. importing a single named exportimport { MyComponent } from “./MyComponent”;// ex. importing multiple named exportsimport { MyComponent, MyComponent2 } from “./MyComponent”;// ex. giving a named import a different name by using “as”:import { MyComponent2 as MyNewComponent } from “./MyComponent”;// exports from ./MyComponent.js fileexport const MyComponent = () => {}export const MyComponent2 = () => {}

Import all the named exports onto an object:

import * as MainComponents from “./MyComponent”;// use MainComponents.MyComponent and MainComponents.MyComponent2here

Default Export: (export default)

One can have only one default export per file. When we import we have to specify a name and import like:

// importimport MyDefaultComponent from “./MyDefaultExport”;// exportconst MyComponent = () => {}export default MyComponent;

The naming of import is completely independent in default export and we can use any name we like.

Image for postwe can use made up names but keep it relevant.

From Documentation:

Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.

Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the ?main? exported value since it will be the simplest to import.

Checkout my other posts:

  1. Why is customer acquisition a wrong metric to measure startup?s growth.
  2. What?s the difference between super and super(props) in ES6.
  3. CurrentTarget vs Target in Js.
  4. A brief introduction of Node, React and NPM.
  5. Getting rid of relative paths in import statement using webpack aliases.

No Responses

Write a response