Angular 9 library namespaces

Szórádi Balázs
2 min readApr 15, 2020

I stumbled upon a namespace problem while upgrading NPM packages to Angular 9. In case the library was used by an application directly, everything was working as expected, but otherwise, in case, the library was used by another library, then I was facing a null provider crash in the Angular core.

ERROR TypeError: token.toString is not a function
at stringify (core.js:489)
at NullInjector.get (core.js:1076)
at R3Injector.get (core.js:16629)
at R3Injector.get (core.js:16629)
at R3Injector.get (core.js:16629)
at NgModuleRef$1.get (core.js:36024)
at R3Injector.get (core.js:16629)
at NgModuleRef$1.get (core.js:36024)
at Object.get (core.js:33773)
at getOrCreateInjectable (core.js:5805)

The problem with this error is that it crashes in the routine that is supposed to log which provider it has a problem with, so you are left clueless, knowing no more than a provider is undefined…

The token is undefined therefore you get the error above.

Solution

Finally, it turned out IVY has a problem with the method I used to export namespaces.

// previous problematic exportbarel.ts
// contains all the stuff exported under the namespace XYZ_FOO
export * from './model/models';
export * from './api/api';
index.ts
// this is how I defined my namespace in ng8 and before
import * as XYZ_FOO from './barel';
export {XYZ_FOO};

Exporting the namespaces the following way resolved the issue, and to be honest, looks way better than the previous solution.

// new corrected exportxyz-foo.ts
// contains all the stuff exported under the namespace XYZ.FOO
export * from './model/models';
export * from './api/api';
index.ts
// updated way of exporting the namespace (works for both libs/apps)
import * as _foo from './xyz-foo';
import * as _bar from './xyz-bar';
export namespace XYZ{
export import FOO = _foo;
export import BAR = _bar;
}

Should you have the same problem, I hope this gives you a hand.

--

--

Szórádi Balázs

Programming in assembly, c, c++, java, javascript, typescript. Interested in 3d graphics, visual effects, demoscene, dsp, c64, cycling, climbing…