kipy kipy - 10 months ago 75
TypeScript Question

Cannot resolve import from index.ts from script located in same directory

I'm working on an angular 2 project written in TypeScript 2 and i'm currently facing an issue with the imports mechanism.

Every sub-folder of my project has an "index.ts" file inside, that is exporting classes the said folder contains.

So, in my "app" directory,
I have

  • app.component.ts

  • app.module.ts

  • app.routes.ts

And then, an index.ts file containing :

export * from './app.component';
export * from './app.module';
export * from './app.routes';

My issue is that I'm not able to import the exported classes from a file that is located in this same directory.

E.g., in my app.module.ts, I want to import the app component.
If I do :

import { AppComponent } from './app.component';

Everything work fine ! No error at compile time and runtime. Life is cool, life is beautiful.

But I can't do the following :

import { AppComponent } from '.'; // or './', or even './index'

The IDE (Visual Studio) actually resolves the import correctly (it compiles with no errors). I even get autocompletion from Intellisence...

But I get this error at runtime :

Error: Unexpected value 'undefined' imported by the module 'AppModule'

And I just don't know why.

Note : I don't have any error by importing from index.ts from subfolders (e.g. I can do import from './core' that also has an index).

Thank you in advance :)

Answer Source

I had the exactly the same issue.

You seem to have circular dependency.

When you write this:

import { AppComponent } from '.';

the resolver goes to index.ts and sees this:

export * from './app.component';

so then it goes to ./app.component and sees this:

import { AppComponent } from '.';

so it goes to index.ts and sees this:

export * from './app.component';

And so on and so forth...

What's odd about this is that you get no warnings, and, depending on the loader, it may actually resolve correctly second time around (so first time you get undefined but in subsequent calls it resolves correctly) - I've spent 4 hours because of a far-less-obvious circular dependency. I strongly argue typescript should raise a warning on these things because it's a proper can of worms.