本文介绍了为什么不“导出默认值"?在Angular中推荐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据打字稿文档(构造模块指南"一节) :

就像出口到顶级商品"一样,可以减少您的摩擦 模块的使用者,引入默认导出也是如此.如果一个 模块的主要目的是容纳一个特定的出口,然后您 应该考虑将其导出为默认导出.这使得两者 导入和实际使用导入要容易一些.

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() { ... }
}

组件的角度文档中(例如),人们看到了这一点:

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

通常,组件或模块的主要目的是容纳一个特定的出口.因此,有没有理由不使用Angular或建议使用export default的原因?

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?

推荐答案

实际原因是这不适用于AOT编译器,但是可以用于JIT编译器.因此,如果您使用的是AOT(或希望继续使用它),请不要导出默认值.另请参见此处:

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:

AoT不允许默认导出-必须全部命名.

Default exports aren't allowed with AoT - they must all be named.

❌不要:

import { Component } from '@angular/core';

@Component({
  template: `
    <div class="example">
      Example component!
    </div>
  `
})
export default class ExampleComponent {

}

✅做:

import { Component } from '@angular/core';

@Component({
  template: `
    <div class="example">
      Example component!
    </div>
  `
})
export class ExampleComponent {

}

这篇关于为什么不“导出默认值"?在Angular中推荐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 03:09