简体   繁体   中英

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

I write 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. 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?

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

A typescript or javascript file can export multiple class( or functions, constants). 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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