Skip to content

Instantly share code, notes, and snippets.

@jhnns
Created February 19, 2016 14:56
Show Gist options
  • Save jhnns/d6aa4e6009427ca4af94 to your computer and use it in GitHub Desktop.
Save jhnns/d6aa4e6009427ca4af94 to your computer and use it in GitHub Desktop.
angular 1 babel plugin idea

angular 1 babel plugin idea

Mitigates angular module boilerplate with ES2015 modules based on naming conventions:

import template from "./modal.html";
import UserService from "./UserService";
import AnotherService from "./AnotherService";

function ModalDirective() {
	return {
		template,
		scope: {},
		link() {
			...
		}
	};
};

... becomes ...

import { angular } from "angular";
import UserService from "./UserService";
import AnotherService from "./AnotherService";

function ModalDirective(UserService, AnotherService) {
	return {
		template,
		scope: {},
		link() {
		
		}
	};
}

export default angular.module("app")
	.directive("Modal", ["UserService", "AnotherService", ModalDirective])

Pseudocode

  1. Parse the imports
  2. If an import name starts with a capital letter and ends on Controller or Service do the following steps:
    1. Store the import name in a record
  3. Add import { angular } from "angular" to the module's root scope
  4. Add export default angular.module("app") to the module's root scope
  5. Parse function names in the module's root scope
  6. If a function starts with a capital letter and ends on Directive, Controller or Service do the following steps:
    1. Add angular.module("app")[postfix](name, [...importNames, fn])" with
      • name being the function's name without Directive if present
      • ...importNames being the list of imports from the import record
      • postfix being the end of the function name .toLowerCase() (e.g. "directive")
      • fn being the function
    2. Add ...importNames as function arguments

Pros

  • Less boilerplate
  • No dependency injection visible in the code

Constraints

  • Function names of directives, services and controllers must be unique across the "app" module
  • Works best if there is only one directive/service/controller per module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment