Reputation: 12813
According to the Typescript documentation (section "Guidance for structuring modules"):
If you’re only exporting a single class or function, use export default
Just as “exporting near the top-level” reduces friction on your module’s consumers, so does introducing a default export. If a module’s primary purpose is to house one specific export, then you should consider exporting it as a default export. This makes both importing and actually using the import a little easier.
Example:
export default class SomeType {
constructor() { ... }
}
In the Angular documentation for components (for example) one sees this:
export class HeroListComponent implements OnInit {
heroes: Hero[];
selectedHero: Hero;
constructor(private service: HeroService) { }
ngOnInit() {
this.heroes = this.service.getHeroes();
}
selectHero(hero: Hero) { this.selectedHero = hero; }
}
Generally, a component's or module's primary purpose is to house one specific export. So, is there a reason why Angular does not use or recommend using export default
?
Upvotes: 17
Views: 10146
Reputation: 982
I don't said export default
is not recommended in Angular. I since it's tottaly up to you and relative to your coding preferences. Some of developers avoid Export Default because of maintainability and refactoring concerns.
But you need to know export default
is now fully supported by Angular. Take this part of the documentation about Lazy loading and default exports for loadChildren() as an exemple.
Regarding to AOT compiler bug, The problem seems to be soved since March 2020 (#11402)
See this related post for more details about it.
Upvotes: 1
Reputation: 3671
The actual reason is that this doesn't work with the AOT compiler, however it will work with the JIT compiler. So if you are using AOT (or want to use it moving forward), don't do export default. See also here:
Default Exports
Default exports aren't allowed with AoT - they must all be named.
❌ DONT:
import { Component } from '@angular/core'; @Component({ template: ` <div class="example"> Example component! </div> ` }) export default class ExampleComponent { }
✅ DO:
import { Component } from '@angular/core'; @Component({ template: ` <div class="example"> Example component! </div> ` }) export class ExampleComponent { }
Upvotes: 22