javascriptecmascript-6es6-modules

`export const` vs. `export default` in ES6


I am trying to determine if there are any big differences between these two, 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';

Are there any differences and/or use cases other than this?


Solution

  • It's a named export vs a default export. export const is a named export that exports a const declaration or declarations.

    To emphasize: what matters here is the export keyword as const is used to declare a const declaration or declarations. export may also be applied to other declarations such as class or function declarations.

    Default Export (export default)

    You can have one default export per file.

    // add.js
    export default function(a, b) {
      return a + b;
    };
    

    When you import you have to specify a name and import like so:

    import add from "./add.js";
    

    You can give this any name you like.

    Named Export (export)

    With named exports, you can have multiple named exports per file.

    // file.js
    export const value = 5;
    
    export function myFunc() {}
    
    export default function(a, b) {
      return a + b;
    }
    

    Then import the specific exports you want surrounded in braces:

    // ex. importing multiple exports:
    import { myFunc, value } from "./file.js";
    // ex. giving a named import a different name by using "as":
    import { value as otherName } from "./file.js";
    
    // use myFunc, value, otherName here
    

    Or it's possible to use a default along with named imports in the same statement:

    import add, { value } from "./file.js";
    

    Namespace Import

    It's also possible to import everything from the file on an object:

    import * as mod from "./file";
    // use mod.value, mod.myFunc and mod.default here
    

    Notes