npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ng-esm

v2.3.0

Published

ES2015 modules and decorators with AngularJS

Downloads

238

Readme

ng-esm

ES2015 modules and decorators with AngularJS, complete with Typescript definition files

  1. Current progress
  2. Motivation
  3. Goals
  4. Usage

Current progress

  • Documentation can still be improved a lot
  • Unit tests are not yet implemented (only example usage as of yet)

Motivation

AngularJS is awesome. The module system in AngularJS when using es2015 import/export statements is... not as awesome. It typically results in a lot of extra wiring code and boilerplate which can be tricky to incorporate into a modern modular workflow.

//# some.component.js
import * as angular from 'angular'; // avoiding globals

export default angular
  .module('is-this-really-needed?', [])
  .component(/* settings */)
  .name;

//# some.module.js
import * as angular from 'angular';
import someComponent from './some.component';

angular.module('might-be-needed', [someComponent]);

It's not uncommon for developers to want to avoid using globals. This results in importing "angular" in every file that want to register a component or service.

import * as ng from 'angular';

It's also not uncommon to want to avoid duplicating magical AngularJS module strings everywhere, which means we want to export the module name to avoid referring to it directly.

export default angular
  .module('is-this-really-needed?', [])
  .component(/* settings */)
  .name;

It's possible to just create one AngularJS module, and stick every directive, component, service and whatnot on that module. One drawback to this can be when a piece of code need to be tested in isolation (e.g. a config function unaffected by other config functions).

Goals

  • Conveniently decorate class as e.g. component/service for reduced boilerplate

  • Allow classes as dependencies to skip exporting AngularJS module strings

  • Provide excellent tooling support via Typescript

  • Match Angular syntax where it makes sense (decorators by themselves increase similarity to ng2)

Usage

Example

// greeter.service.js
import { Service } from 'ng-esm';

const greeters = new Set();

@Service()
export class GreeterService {
  sayHello(name) {
    for (let greeter of greeters) {
      greeter.greet(name);
    }
  }
  register(greeterComponent) {
    greeters.add(greeterComponent);
  }
  unregister(greeterComponent) {
    greeters.delete(greeterComponent)
  }
}
// greeter.component.js
import { Component } from 'ng-esm';
import { GreeterService } from './greeter.service';

@Component({
  dependencies: [GreeterService]
  bindings: {
    greeting: '@'
  },
  template: '<p>{{ $ctrl.greeting }} {{ $ctrl.name }}</p>'
})
export class MyGreeter {
  constructor(GreeterService) {
    this.name = 'John Doe';
    this.GreeterService = GreeterService;
  }
  $onInit() {
    this.GreeterService.register(this);
  }
  $onDestroy() {
    this.GreeterService.unregister(this);
  }
  greet(name) {
    this.name = name;
  }
}
// greeter.module.js
import { NgModule } from 'ng-esm';
import { MyGreeter } from './greeter.component';

@NgModule('greeter', [MyGreeter])
class Greeter {}

If we would add greeter as a dependency to an AngularJS module, we could then use <my-greeter greeting="Hello"></my-greeter> to create a component, and the GreeterService.sayHello('Gabe') to make all greeter components say hello.

NgModule

import { NgModule, ngModule } from 'ng-esm';

@NgModule([/* string/decorated-class dependencies */])
class Sauce {}
// module name: Sauce

@NgModule('awesome', [/* string/decorated-class dependencies */])
class Sauce {}
// module name: awesome

@NgModule({
  // all options are optional
  name: 'sweet',
  dependencies: [/* string/decorated-class dependencies */],
  values: {
    myVal: 'available to DI as "myVal"'
  },
  constants: {
    myConst: 'available to DI as "myConst"'
  }
})
class Sauce {}
// module name: sweet


// useful for seldom used api's, e.g. animation, decorator
// create a new AngularJS module with generated name
ngModule();
// specify name
ngModule('myModule');
// specify dependencies (generated name)
ngModule(null, []);
// or both
ngModule('anotherModule', []);

Component

import { Component } from 'ng-esm';

@Component({
  name: 'myGreeter', // optional, camelCased class-name when missing
  dependencies: [], // optional, decorated classes or strings

  template: '<p>Hello world!</p>'
  // All `angular.module().component()` settings allowed
})
export class MyGreeter {
  $onInit() {}
}

Directive

It's only practical to use this decorator if the directive uses a controller, and not compile/link with dependency injection.

import { Directive } from 'ng-esm';

@Directive({
  name: 'myDirective', // optional, camelCased class-name when missing
  dependencies: [], // optional, decorated classes or strings
  bindToController: true,
  scope: {},
  restrict: 'A',
  require: {
    model: 'ngModel'
  }
  // All `angular.module().directive() settings allowed
})
export class MyDirectiveCtrl {
  constructor($element) {
    this.$element = $element;
  }

  $onInit() {
    this.model.parsers.push(v => !v);
  }
}

Filter

// Typescript example
import { Filter, FilterTransform } from 'ng-esm';

@Filter({
  name: 'percent', // optional, camelCased class name when missing
  dependencies: [] // optional, decorated classes or strings
})
export class PercentFilter implements FilterTransform {
  constructor(/* Injectables */) {}

  transform(value: number, decimals: number = 2) {
    return `${value.toFixed(decimals)} %`;
  }
}

Service

import { Service } from 'ng-esm';

@Service({
  name: 'myService', // optional, class name when missing
  dependencies: [] // optional, decorated classes or strings
})
export class MyService {
  constructor(/* Injectables */) {}

  serviceMethod() {}
}

Factory/Provider

import { Factory, Provider, FactoryCreator } from 'ng-esm';

// @Factory and @Provider has identical signatures for both decorator and class

@Factory({
  name: 'myFactory', // optional, class name when missing
  dependencies: [] // optional, decorated classes or strings
})
export class MyFactory implements FactoryCreator {
  constructor(/* Injectables */) {}

  $get(/* Injectables */): any {
    // Return an instance of the service
    return {};
  }

  // `@Provider()` may have additional methods for configuring the service during the config phase
}

Note: When using @Provider(), only constants may be available to inject. This is due to angulars lifecycle.

Config/Run

// Typescript example
import { Run, Config, OnInit } from 'ng-esm';

@Run([/* string/decorated-class dependencies */])
export class SetupStuff implements OnInit {
  constructor(private someService) {}

  $onInit() {
    this.someService.doSomething();
  }
}

@Config([/* string/decorated-class dependencies */])
export class SetupMoreStuff implements OnInit {
  constructor(private someProvider) {}

  $onInit() {
    this.someProvider.doSomethingElse();
  }
}

State

import { State, resolve, Resolve } from 'ng-esm';

@Resolve({ aNumber: () => 123 })
@State({
  /*
    regular ui-router state configuration
    `controller` is not needed, as the decorated class is used
  */
  name: 'app.contacts',
  url: '/contacts',
  template: '<p>Foo!</p>'
})
export class ContactsController {
  constructor(aNumber) {}
}

@State({
  name: 'app.contacts.detail'
})
export class ContactsDetailController {
  constructor(aBool) {}

  @resolve
  static aBool() {
    return true;
  }
}

miscellaneous stuff

import { controllerAs, getNgModule, getModuleIds } from 'ng-esm';

// Set the default "controllerAs" name for component/directive/state
controllerAs('vm');

// Fetch an AngularJS module for string or decorated class
getNgModule('app.contacts');

// Returns an array of strings with all registered AngularJS modules ids
getModuleIds();

Note: controllerAs() should be set before any controllers are registered. Also don't forget to load this option for unit tests. Set this option in a module loaded right after AngularJS for both tests and app code.