XGHeaven
XGHeaven

Reputation: 1736

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?

Upvotes: 0

Views: 118

Answers (5)

yuan zhu
yuan zhu

Reputation: 96

If you use 'import some from somecomponent' unless there is only one export moudel in the somecomponent,if there are more than one export moudle,you must use {} to specified import which moudle

Upvotes: 0

Shanon Jackson
Shanon Jackson

Reputation: 6561

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

Upvotes: 0

Sandip Jaiswal
Sandip Jaiswal

Reputation: 3730

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"

Upvotes: 1

user4676340
user4676340

Reputation:

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.

Upvotes: 0

Igor Kurpis
Igor Kurpis

Reputation: 11

If you add default before class then you gonna be able to import in in the same way as in React/Vue.

Upvotes: 1

Related Questions