thorn0 / babel-plugin-transform-ng1-jsx

Type-checked templates for Angular 1
MIT License
1 stars 4 forks source link

babel-plugin-transform-ng1-jsx

A proof of concept of type-checking Angular 1 templates with TypeScript.

The idea is to use JSX for the templates, to type-check them with TypeScript, and to convert them into the usual HTML string representation with a Babel plugin.

The solution consists of two parts:

  1. Type definitions for JSX (ng1-jsx.ts)
  2. The Babel plugin

Written in JSX, templates become just part of the TypeScript code. Include the type definitions with a /// <reference path="..." /> comment, and use the --jsx preserve mode ("jsx": "preserve" in tsconfig.json) for the TypeScript compiler to understand and emit JSX. Finally, use the Babel plugin to compile JSX into HTML strings.

Important differences between HTML and JSX

In the first place, this technique is supposed to be used with Angular 1.5 and its component style directives. If you use the component approach, most of the time the only variable used in the template is a reference to the controller ($ctrl by default). Just declare this variable above the JSX block. Don't assign anything to it as it's needed only for the type-checking.

What it looks like

angular.module('example').factory('parentViewTemplate', function() {
  let $ctrl: ParentView; // this variable is needed only to check the types
  return (
    <div class='ooo'>
      { $ctrl.record.id }
      <ChildView someParameter="aaa" onSave={ ({data}) => $ctrl.save(data) } />
      <span ng-if={ $ctrl.flag }>foo</span>
    </div>
  );
});

is compiled to

angular.module('example').factory('parentViewTemplate', function () {
    var $ctrl;
    return '<div class="ooo">{{$ctrl.record.id}}<child-view some-parameter="\'aaa\'" on-save="$ctrl.save(data)"></child-view><span ng-if="$ctrl.flag">foo</span></div>';
});

Complete Example

You can find an example to play with in the example folder. Run npm run build in that folder to compile it.

Issues / TBD

Links