Hysen Labs
Open-source project
bcherny/ngimport avatar
bcherny

ngimport

Easy to use ES6 imports for $http, $log, and other Angular 1 services

100 stars5 forksTypeScriptLicense varies
01
DEEP OPEN-SOURCE ANALYSIS

ngimport, or a way out of Angular 1 DI

Import $http and $log as plain ES6 modules instead of injecting them, keep full TypeScript safety, and get a migration path toward Angular 2 or React without rewiring the app all at once.

02
DEEP OPEN-SOURCE ANALYSIS

Why Angular 1 DI feels dated

Angular 1 dependency injection made sense back when JavaScript had no module standard. With CommonJS and then ES Modules in place, DI mostly adds friction and makes code less portable. Add TypeScript and it gets worse: a typed service class whose dependencies arrive through a closure cannot be exported directly, so people end up writing a second interface just to export it, and constructor-based injection blocks passing arguments to a new instance.

03
DEEP OPEN-SOURCE ANALYSIS

What you get instead

The whole approach is standard imports. No proprietary DI, no lock in, and constructors are free to take ordinary arguments. It avoids duplicated TypeScript interface declarations, and the familiar testing tools still apply: mock Angular dependencies with $provide and assert HTTP requests with $httpBackend. The project also works as an adapter, so a codebase can move over to imports piece by piece.

04
DEEP OPEN-SOURCE ANALYSIS

The wrapping trick

The same technique works for legacy modules of your own. Instead of DIing a service, expose it together with its typings and then write a plain import. The README shows a fooService example that ends as an ES6 import, leaving the freedom to port that service to TypeScript or ES6 at your own pace.

05
DEEP OPEN-SOURCE ANALYSIS

Sharp edges

Two caveats stand out. Angular builtins like $http and $rootScope stay undefined until the app bootstraps, because of how Angular builds injectors, so avoid using them at the top level or bootstrap first. And when transpiling to CommonJS, destructure the import rather than importing a default value, or the consumer keeps pointing at the old undefined reference after an update.

06
DEEP OPEN-SOURCE ANALYSIS

Still on the todo list

A short todo section lists services not yet covered: $animate, $animateCss, $aria, $cookies, $provide, $resource, $rootRouter, $route, $routeParams, $routerRootComponent, $sanitize, $swipe, and $touch. For a library aimed at un-injecting Angular, that list is a reasonable map of what still waits to be wrapped.

08
DEEP OPEN-SOURCE ANALYSIS

Official sources

09
Community notes

Community notes