Component Generator for AngularJS, Angular 2, Aurelia​


I believe developers should own their code generation story. The value in owning your code generation is that when platforms change, APIs change, language grammar is enhanced, you can easily refactor your templates and not miss a beat. I also believe that owning your code generation story is a forcing function for thinking out how your application works, is wired up, and how to unit test it.

This tool provides templates that you must edit before generating any code.

What?  No ready-made templates?  Karl, are you nuts?  Why?

Let’s think about code generation templates for a minute. Templates are used to create language specific output.  Developers are using many flavors of JavaScript today: ES5, ES6, ES6 with ES7 experimental features, TypeScript, Coffee Script, etc. Stylesheet files can be written using LESS, SASS, SCSS, or CSS.

What language should I use to write the templates?  I use ES6, but not everyone does.

Let’s think about how Angular apps are structured and wired up.  Check ten blog posts, and you’ll read about ten valid ways to structure and wire up an Angular SPA app.

Small apps are wired up differently than medium or large apps.  Some put small modules in a single folder, whereas a medium-sized module may be within a single parent folder, with each component in a separate folder.

Developers doing unit testing will structure their component wire up differently to better support testing scenarios without having to load Angular for a component or controller unit test.  Not loading Angular for each unit test significantly speeds up your unit tests.

Based on the above language, structure, and wire up options, providing default templates would provide zero value.

Your Small Part

You’ll edit the empty template files for the component based SPA frameworks you author applications for such as AngularJS, Angular 2, or Aurelia. Having you edit your templates provides the best solution for this tool supporting many different: JavaScript flavors, AngularJS coding styles, and component wiring up strategies. Additionally, you’ll be the proud owner of your code generation story.

This tool uses Underscorejs templates that are easy to author, usually requiring a minute or two. However, if your scenario requires it, you can swap out the template engine.

More Than a Tool

My first version of this tool was written in less than two hours as single ES6 file and worked great. It didn’t have any tests but worked perfectly for my one scenario which was, Angular 1.5.9 components and ES6.

Then my mentoring and scope creep genes kicked into high gear, and I spent a few days and several versions to produce this tool.

I didn’t want to miss an opportunity to share a tool that I think will benefit many developers across languages, SPA frameworks, and scenarios. But to accomplish this goal, the tool would require 100% test coverage, work for any JavaScript language and any SPA component based framework.

I hope that others can learn from the architecture, code, and unit tests presented here. I welcome both positive and negative feedback to improve the tool and code.

This tool was also a forcing function for me to dive deep into authoring testable Node.js tools using ES6. It took me a little time, learning the testing tools, but when I refactored the code, having 100% test coverage paid off in spades.


During my career as a Software Engineer and Architect, I’ve always written tools to increase my productivity and accuracy. Tools like XAML Power Toys or this tool came about because I found myself repeating the same task over again, and knew the computer is capable of making me infinitely more productive.

Two weeks ago I started writing an AngularJS 1.5.9 component based application.  AngularJS components are similar in concept to Angular 2 and Aurelia components although the syntax and implementation are a little different.

After creating my second component, I stopped to write this tool. I’m not going to perform mundane, repetitive tasks like creating: folders, components, controllers, templates, tests, and CSS files; this is a perfect assignment for a tool.

In addition to creating folders and files, the tool leverages user editable templates for generating code that matches your requirements and coding style. The ability to generate boiler maker code yields a significant increase in productivity.

What You’ll Learn

  • Features of the tool
  • Tool Architecture
  • Requirements
  • Installation
  • Local development installation
  • Local production installation
  • Command line usage
  • Editing Templates


  • Getting Started
  • Modifying the tool
  • Unit testing the tool


  • Node.js command line utility, written using ES6 and TDD methodology
  • Cross-platform Windows, Mac, and Linux (thanks to Node.js)
  • User editable templates drive the generated code
  • Create components for any JavaScript framework like AngularJS, Angular 2, and Aurelia
  • Separating templates by framework enables supporting multiple frameworks
  • Component output folder is optionally created based on a command line option
  • Component controller file is optionally generated based on a command line option
  • Component unit test file is optionally generated based on a command line option
  • Component CSS file is optionally generated based on a command line option
  • You can modify anything about this tool, make it fit like a glove for your workflow

Tool Architecture

This object-oriented application tool was written using ES6. I have separated the functionality of the application into small single-responsibility classes. Besides good application design, it makes understanding and unit testing much easier. When I think of this tool, a .NET Console application immediately comes to mind.

I wrote Guard clauses for every constructor and method. I always add guard clauses, even on private methods, irrespective of language because I am a defensive software engineer. Writing guard clauses requires no extra effort given tools like Resharper and the ubiquitous code snippet feature in most editors and IDEs. Guard clauses future proof code in maintenance mode when another developer makes a false assumption while editing, next think you know a customer is filing a bug.

In some of the classes, I have refactored small sections of code into a method. Doing this makes the code easier to read, comprehend, and simplifies unit testing.


  • ApplicationError – deriving from Error, an instance of this class is thrown when a user error caused by improper command line usage occurs. It permits the top-level try catch block in the ComponentCreator to perform custom handling of the error.
  • CommandLineArgsUtility – provides functions related to command line arguments.
  • ComponentCreator – performs validation and writes the templates.
  • IoUtility – wrapper around Node.js fs.
  • Logger – wrapper around Console
  • TemplateItem – wrapper around a supported framework, exposes all data as immutable
  • Templates – stores collection of TemplateItems, provides immutable data about code generation templates.

The entry point for the tool is index.js.  This module instantiates a TemplateItem for each supported framework, creates all of the required dependencies for the ComponentCreator and injects them, then invokes the create method on the ComponentCreator instance.

The reason for creating and injecting all external dependencies in the root of the application is to enable unit testing. Dependencies injected using constructor injection can easily be stubbed or mocked.

I have successfully used this type of architecture for writing other complicated Node.js applications.


  • Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
  • Chai – is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.
  • Istanbul – full featured code coverage tool for Javascript
  • Mocha – is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun.
  • Sinon.js – Standalone test spies, stubs, and mocks for JavaScript.
    No dependencies and works with any unit testing framework.
  • Sinon-Chai – provides a set of custom assertions for using the Sinon.JS spy, stub, and mocking framework with the Chai assertion library. You get all the benefits of Chai with all the powerful tools of Sinon.JS.


  • Node.js  (install either LTS or Current versions.  Personally I use the Current version.)

On Mac’s I don’t recommend installing Node.js from the Node.js website. If you do, upgrading is a PIA.

For Mac users, use brew. After installing brew, run this command from a terminal:

brew install node

If you use brew, future upgrading or uninstalling Node.js on your Mac is a breeze.


To help understand how this application is setup and how unit testing is setup and invoked, please read my blog post:


Ensure you have installed above requirements.

Download or clone the Component Generator repository here.

Open a terminal or command window, and then navigate to the root folder of the tool and run this command.

npm install

Next, run the unit tests and see the coverage report by executing this command:

npm test

Running the unit test also runs the Istanbul code coverage tool which outputs a detailed coverage report in the /coverage/lcov-report/index.html file.

Local Development Installation

During development, testing, and editing of your Node.js command line tools you’ll need to set up a symbolic link so you can execute your tool from any folder. Setting up a symbolic link instead of installing your Node.js package globally, allows you to continue editing the tool’s code, while at the same time, being able to execute the tool from any folder on your computer.

Mac and Linux

From the root folder of the tool, open a terminal or command window and run this command:

npm link

To test you development installation run this command:


The tool will display the command line usage.

Navigate to another folder and rerun the gencomponent command.  You should get the same output.


You MUST give yourself Full Permissions on the /node_modules folder before proceeding.

Follow the above steps for Mac and Linux.

Local Production Installation

This step is optional.  If you like the convenience of being able to edit your templates or change the tools code, while at the same time being able to invoke the tool from any folder then, by all means, skip this step.

If you want to install the tool globally, or want to install the tool on other machines, then follow these steps.

Before proceeding, you need to remove the symbolic link you created in the above steps.

Navigate to the root folder of the tool, open a terminal or command window and run the following command:

npm unlink
Window, Mac, and Linux

Navigate to the root folder of the tool, open a terminal or command window and run the following command:

npm install -g

You can now invoke the tool from anywhere on your machine.

After installation, if you need to modify the tool or template, uninstall the tool globally, make the changes and reinstall it globally.

Command Line Usage

Before proceeding, ensure you have created a symbolic link for the tool, or installed it globally.

gencomponent (component name) [-(framework)] [--ftsc]

The component name is required to generate a component.

The framework is optional and defaults to ‘ng’ if not supplied. Default framework can be changed by modifying the code.  Default valid options:

  • -ng
  • -ng2
  • -aurelia

Code generation options are prefaced with a double dash  (–), are optional, and can be in any order. The valid options are:

  • f = create a component folder
  • t = create a component unit test file and controller unit test file for the optional controller
  • s = create a component CSS file
  • c  = create a component controller file

If invalid arguments are provided or you attempt to create a component that already exists, an error message will be displayed at the command line.

Usage Examples

1. Show the command line usage message.


gencomponent ?

2. Create the Sales component in the current folder along with the sales.component js, and sales.template.html files. Templates are selected from the default /templates/ng folder.

gencomponent Sales

3. Create the Sales component in a new component folder named Sales along with the sales.component js, sales.controller.js, sales.template.html, sales.component.spec.js, sales.controller.spec.js, and sales.template.css files.  Templates are selected from the default /templates/ng folder.

gencomponent Sales --ftcs

4. Create the Sales component in the current folder along with the sales.component js, sales.component.spec.js, and sales.template.html files. The templates are selected from the /templates/aurelia folder.

gencomponent Sales -aurelia --t

5. Create the SalesDetail component in a new component folder named SalesDetail along with the salesDetail.component.js, salesDetail.component.spec.js, salesDetail.controller.js, salesDetail.controller.spec.js, and salesDetail.template.html files. The templates are selected from the /templates/ng2 folder.

gencomponent SalesDetail -ng2 --ftc

You can easily modify this tool to handle more or less supported frameworks and change the file naming conventions.

Editing Templates

Please read Underscorejs template documentation, it’s very short.

Template engines allow the template author to pass a data object to methods that resolve the template and produce the generated code.

This tool passes a rich data object that you can use inside your templates.

gencomponent SalesDetail

The below template data object was hydrated and passed to the template engine when the tool was invoked with SalesDetail as the desired component.

{ componentName: 'SalesDetail',
 componentSelector: 'sales-detail',
 componentImportName: 'salesDetail.component',
 controllerImportName: 'salesDetail.controller',
 componentImportNameEnding: '.component',
 controllerImportNameEnding: '.controller',
 templateFileNameEnding: '.component.html',
 componentFileNameEnding: '.component.js',
 controllerFileNameEnding: '.controller.js',
 componentSpecFileNameEnding: '.component.spec.js',
 templateCssFileNameEnding: '.component.css' }

This snippet from the below HTML file shows the syntax for injecting the componentName property value into the generated code.

<%= componentName %>

The below HTML can be found in the /temples/ng/componentTemplate.html file. This demonstrates consuming a data object property in a template.

<h2>Component Generator Data Object</h2>
<p>These are the data properties available in all template files.</p>
<p>componentName = <strong><%= componentName %></strong></p>
<p>componentSelector = <strong><%= componentSelector %></strong></p>
<p>componentImportName = <strong><%= componentImportName %></strong></p>
<p>controllerImportName = <strong><%= controllerImportName %></strong></p>
<p>componentImportNameEnding = <strong><%= componentImportNameEnding %></strong></p>
<p>controllerImportNameEnding = <strong><%= controllerImportNameEnding %></strong></p>
<p>templateFileNameEnding = <strong><%= templateFileNameEnding %></strong></p>
<p>componentFileNameEnding = <strong><%= componentFileNameEnding %></strong></p>
<p>controllerFileNameEnding = <strong><%= controllerFileNameEnding %></strong></p>
<p>componentSpecFileNameEnding = <strong><%= componentSpecFileNameEnding %></strong></p>
<p>templateCssFileNameEnding = <strong><%= templateCssFileNameEnding %></strong></p>

Template Folders

  • /ng – AngularJS
  • /ng2 – Angular 2
  • /aurelia – Aurelia

Available Templates

  • Component – always generated
  • Component Template – always generated
  • Controller – optionally generated
  • Component Unit Test – optionally generated
  • Controller Unit Test – automatically generated if the Controller and Component Unit Test is generated
  • Component Template Stylesheet – optionally generated

Workflow for Editing Templates

Before diving into template editing, you need to know exactly what the outputted generated code needs to look like.

You’ll need to decide on your application structure and wiring up.  Will you put your controllers inside the component file or keep them in separate files? Are you going to write unit tests?

I recommend, writing several components, w0rk out the details, identifying repeated code such as imports or require statements, and commonly used constructor injected objects.

In the below example, I have an existing About controller that represents how I would like my controllers to be generated.

Copy the code to generate into the appropriate template file, and then replace the non-repeating code with resolved values from the template data object.

In the below example, I copied the About controller into the componentTemplate.controller.js file and then replaced the “About” name with the componentName data object property.

class AboutController {
   constructor() {

export default AboutController;

This below template will generate the above code.

class <%= componentName %>Controller {
    constructor() {

export default <%= componentName %>Controller;

Now repeat the above steps for each template and for each framework you’ll be performing code generation.

Note that some templates will be empty, this is normal for .css and possibly .html files. But at least you didn’t have to waste precious time creating the file.


Getting Started

This 8-minute video explains how to get started with this tool.

Modifying the Tool

This 11-minute video explains how to modify:

  • templates
  • frameworks
  • file naming conventions
  • template engine

Unit Testing the Tool

This 23-minute video explains unit testing this tool.


Writing your own cross-platform, command-line tools using Node.js is fun.

Having 100% test coverage is not easy and takes time. Just know that your customers and fellow developers will appreciate you putting the effort into a release with 100% test coverage.

Have a great day.

Just a grain of sand on the worlds beaches.


One comment

  1. Pingback: .NET Unit Testing Tools | Oceanware

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s