What is the difference between export and export default?

Asked

Viewed 4,230 times

10

What is the difference between using the reserved word export and export default. For example:

export class Helper { } 

export default class Helper { } 
  • 1

    Related: https://answall.com/q/360161/27190

1 answer

14


Both commands are used to create modules, and allow that when importing into another file, can be used everything in that module.

The main difference is, as its name suggests (default), the export default is the member (class, variable, const, etc.) exposes itself by default in that module and therefore, there can only be one default member being exported per module.

What is the advantage of this? Unlike an explicit or named export, the default does not need to be referenced with the same name when imported.

Taking the example of the question: export default class Helper { }

This could be imported so:

import abobrinha from 'nome-do-module';
var a = new abobrinha();

This is possible because it is the default of that module, you can import with any name that will always reference that member.

Already the named export, has to be imported with exactly the same name, because it allows to export several members within the same module, because it would be impossible to know which member we want to use.

To illustrate, imagine this exported module:

export class Helper { } 
export class Logger { }

When importing, you could not use another name like this, as it would not be possible to know from which member we are referring:

import abobrinha from 'nome-do-module';

Must follow the names with which they were exported:

import { Helper, Logger} from 'nome-do-module';

More details here: Mozilla/export

  • 1

    when I use export default no member gets export right? So that’s why the default export does not expose any property of my export ? type with export can access some method of my class, already with export default no.

  • 1

    yes gets exposed, is a export after all, but as it is default can only export one member per module in this way

  • even since name is not required, could export an anonymous Function until: export default function () { algum código };

  • the name of the import (export default is symbolic in this case) a reference to my file, right

  • That would be like, "Whatever’s in that file with that name" :)

  • So that’s why I can’t access a static method with export default, just giving new

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.