ajmajmajma ajmajmajma - 10 days ago 6x
Javascript Question

Javascript (ES6), export const vs export default

I am trying to determine if there is any big differnce between these 2 other than being able to import with

export default
by just doing :

import myItem from 'myItem';

And using
export const
I can do :

import { myItem } from 'myItem';

I am wondering if there are any differences and/or use cases other than this. Thanks!


It's a named export vs a default export. export const is a named export with the const keyword.

Default Export (export default)

You can have one default export per file. When you import you have to specify a name and import like so:

import MyDefaultExport from "./MyFileWithADefaultExport";

You can give this any name you like.

Named Export (export)

With named exports, you can have multiple named exports per file. Then import the specific exports you want surrounded in braces:

// ex. importing multiple exports:
import {MyClass, MyOtherClass} from "./MyClass";
// ex. giving a named import a different name by using "as":
import {MyClass2 as MyClass2Alias} from "./MyClass2";

// use MyClass, MyOtherClass, and MyClass2Alias here

Or import all the named exports onto an object:

import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClass.MyOtherClass here

You can use a default export or named exports or both at the same time. The syntax favours default exports though because they are slightly more concise (See the discussion here).

Note that a default export is actually a named export with the name default so you are able to import it by doing:

import {default as MyDefaultExport} from "./MyFileWithADefaultExport";