1

Not sure if the title is clear enough. Feel free to suggest improvements.

I've noticed that the components I'm designing tend to have a bunch of imports. Some of them are duplicated in the importing component. Intuitively, I feel that I'm making it work but sensing code smell.

Suppose we want a monkey to have a banana.

import { Banana } from "./banana";
@Component
export class Monkey { }

Now, some dude wants to own a monkey.

import { Monkey } from "./monkey";
@Component
export class Dude { }

But what if the dude's also hungry and wants a banana for himself too?

import { Monkey } from "./monkey";
import { Banana } from "./banana";
@Component
export class Dude { }

This seems ineffective and redundant to me. The second import appears superfluous since the dude already has a banana through the monkey.

Is it a proper way to declare the import hierarchy in Angular? Or is there a like-a-boss'y way to decrease the scroll payload when looking into the gazillions of imports in each file?

If there isn't a better way, I'd be delighted to see a motivation for this atrocity for a reference mass.

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

1 Answers1

1

You can export from other files to make identifiers available from multiple files from using a single import:

import { Monkey } from "./monkey";
export { Monkey } from "./monkey"; // re-export
@Component
export class Dude { }

See also https://angular.io/docs/ts/latest/glossary.html#!#B

This can lead to hard to find errors though if there are cycles. See Angular 2 DI Error - EXCEPTION: Can't resolve all parameters

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • It depends on the `--module` target. If you use `--module system`, then `Monkey` will only be imported once. If you use `--module commonjs` then two `require` calls are emitted. `system` is a superior format for transpiling as it preserves ES Module semantics with the highest fidelity available, including correct, spec compliant circular reference support. – Aluan Haddad May 08 '17 at 09:01
  • Oh boy... That looks even more confusing import/export, hehe. Thanks for the answer. I think I'll keep to the verbose version for now. Any ideas on why it's designed like that? – Konrad Viltersten May 08 '17 at 09:42
  • Hard for me to answer, because for me it looks quite consistent and logical. Why would you want to have something exported implicitly? I guess your expectations depend on where you come from. If you come from a strongly typed language like C#, Java, Go, ... this behavior will be what you expect, if you come from other languages you might be used to different behavior (don't know any myself, but I'm a strong believer in strongly typed). – Günter Zöchbauer May 08 '17 at 09:46