简体   繁体   中英

Import class in nested module typescript

I'm trying to create hybrid angular 1 + angular 2 with webpack I have a problem with nested module

//a.ts

module a.b.c {
   export class A {
  }
}

//b.ts

 module a.b.c {
   export class B extends A {
  }
}

Code compiling but I'm getting A is undefined I tried import in various of ways but nothing seems to work What am I'd doing wrong?

You need to add a reference to a.ts in b.ts.

So, just edit your b.ts as following:

/// <reference path="./a.ts" />
  module a.b.c {
   export class B extends A {
     public second;
  }
}

In addition, you need to include the a.ts before b.ts in your html file:

<script src="./a.js"></script>
<script src="./b.js"></script>

Otherwise, you will get an error.

That's the way it worked before, but now when we added webpack i read that using reference is not best practice, and webpack not compiling it.

If i just remove the module, than there is not problem. but like you said this is a legacy code with lots of internal modules. If there is no good way of doing that, and the best practice is to remove the module than we may just do that.

Ok, so i'll start by saying again there is indeed no really good way to do this with webpack, and unless this is an enormous project, moving to external modules is the way to go.


if most of your files look like this:

//a.ts

module a.b.c {
  export class A {}
}

//b.ts

module d.e.f {
  export class B extends a.b.c.A
}

Than it's relatively easier, you just do:

//a.ts

export module a.b.c {
  export class A {}
}

//b.ts

import {a} from './a';
module d.e.f {
  export class B extends a.b.c.A
}

However, in the example you gave, you have two files composing the same namespace\\internal module - abc . This is harder to deal with and you'll need to do some ugly stuff like:

//b.ts

import {aImported} from './a';
module a.b.c {
  export class B extends aImported.b.c.A
}

In this solution, your files are external modules and they export internal modules.


There is also a different approach, which is to take all your old code, and compile + concat it old school using Gulp\\Grunt, before passing the resulting js file to webpack. I did this in the past and I regret it and has since moved away from it. But it does require the least amount of changes to code which is the main benefit of it. Overall, I think it's even worse than the previous solution...

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