Using components from external node modules


#1

Hi,

I’m developing both a mobile app (based on ionic2 ofc) and a webapp (standard angular2) that will share a lot of common functionality, including UI components.

The blog post Hybrid mobile apps: sharing logic between Angular2 and Ionic2 apps describes a nice approach of using a node module to extract common functionality and sharing it using npm link.

It works like a charm – except when DI is involved.

If you look at the code linked in the blog post, you will find, that they defined a @Component (FooComponent) in their shared module, but didn’t use it in the web web or mobile app – for good reason as it turned out: When including directives: [FooModule] the mobile (ionic) app it refuses to load telling me No Directive annotation found on FooComponent. In the “vanilla” angular2 web app it works flawlessly, though.

I traced it down to the fact, that there are actually two instances of the ComponentMetaData function created in the ionic app. FooComponent gets annotated with one, but the check in DirectiveResolver.resolve is performed with the other. Boom.

The fact, that it works in the web app makes me believe that it has something to do with Ionic’s custom bootstrapping.

Questions:

  • has anybody successfully used a component defined in an external node module within an Ionic app?
  • if yes, is there an example for this somewhere?
  • And why doesn’t it work in that sample code? (and in my code which is modeled after that?)

All hints are highly appreciated!

Thanks in advance and kind regards,
Markus


#2

There may be a way to deal with this using browserify, but I don’t know it. If you are willing to try using webpack, see some of the solutions in this issue. There is also a link at or near the bottom of that discussion that shows exactly the aliases I needed to use to get npm link working with Ionic. If you do this correctly, there should only be one copy of @angular/compiler in your build and your DI problems should be solved.


#3

thanks for these hints!

When looking at the app.bundle.js, it doesn’t seem like there are two copies of @angular included…

I guess I will have to try out a few more things tomorrow then (already late night here :slight_smile:).

However, I think the current situation is very unsatisfying: The ionic-cli creates a gulp build, but with that I cannot use Components from another module out of the box – something, that doesn’t seem too exotic to me.


#4

Yeah, I bashed my head against it when trying to run bleeding-edge Ionic out of github. At this point, I think the fundamental problem lies with npm itself, and the best we can do is leverage what bundlers can do to mitigate it.