gpt4 book ai didi

angular - 为什么不在 Angular 中推荐 "export default"?

转载 作者:太空狗 更新时间:2023-10-29 17:16:51 27 4
gpt4 key购买 nike

根据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.

例子:

export default class SomeType {
constructor() { ... }
}

Angular documentation for components (例如)一个人看到这个:

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; }
}

通常,组件或模块的主要目的是容纳一个特定的导出。那么,Angular 不使用或不推荐使用 export default 有什么原因吗?

最佳答案

实际原因是这不适用于 AOT 编译器,但它适用于 JIT 编译器。因此,如果您正在使用 AOT(或想继续使用它),请不要导出默认值。另见 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 {

}

关于angular - 为什么不在 Angular 中推荐 "export default"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45962317/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com