简体   繁体   English

为什么要用角度的方法从“ some.component.ts”中使用“ import {SomeComponent}”,而不是从“ some.component.ts”中使用“ import SomeComponent”?

[英]Why angular use `import { SomeComponent } from 'some.component.ts'` instead of `import SomeComponent from 'some.component.ts'`

I write React/Vue. 我写React / Vue。 As usual, I like to export/import a default component. 和往常一样,我喜欢导出/导入默认组件。

// export
export default class SomeComponent from Component {
    // blahblah
}

// import
import SomeComponent from './some.js'

But when I use angular2+, I found a strange thing. 但是当我使用angular2 +时,发现了一件奇怪的事情。 It uses destructive import/export form. 它使用破坏性的导入/导出形式。

// export
@Component({/* ... */})
export class SomeComponent {
    // blahblah
}

// import
import {SomeComponent} from './some.component.ts'

Why? 为什么? I think it a little troublesome. 我觉得有点麻烦。 It's defined by Typescript rules or contributor? 它是由Typescript规则或贡献者定义的?

如果您在class前添加default ,那么您将能够以与React / Vue中相同的方式导入。

A typescript or javascript file can export multiple class( or functions, constants). 一个打字稿或javascript文件可以导出多个类(或函数,常量)。 Due to this behaviour you export your class( or functions, constants) in this fashion: 由于这种行为,您可以通过以下方式导出类(或函数,常量):

export class MyClass{}

and import in this fashion: 并以这种方式导入:

// import
import {MyClass} from './myClass.ts'

If you are sure that you will export only single class( or functions, constants) then just use following syntax: 如果确定只导出单个类(或函数,常量),则只需使用以下语法:

//export
export default class MyClass{}
//import
import MyClass from "./myclass.ts"

This is the standard behavior. 这是标准行为。

It allows you to export several things out of your file. 它允许您从文件中导出一些内容。

For instance 例如

export class MyClass {}
export const MyClassMockedForTesting = {};

But if you want to change that, you can use the default keyword like so 但是,如果要更改此设置,可以使用default关键字,如下所示

export default class MyClass {}

It will export your class and you won't need brackets anymore. 它将导出您的课程,您将不再需要括号。

Angular Doesn't use default imports on its packages because default imports are not good. Angular在其软件包上不使用默认导入,因为默认导入效果不好。 Other people have covered why in seperate posts so i'll link to one here. 其他人在单独的帖子中介绍了原因,因此我将在此处链接到该帖子。 https://blog.neufund.org/why-we-have-banned-default-exports-and-you-should-do-the-same-d51fdc2cf2ad https://blog.neufund.org/why-we-have-banned-default-exports-and-you-should-do-the-same-d51fdc2cf2ad

如果您使用“从某组件导入某些组件”,除非在某组件中只有一个出口组件,则如果有多个出口组件,则必须使用{}指定要导入的组件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM