Category Archives for TypeScript

Winning With Web Components

The web is always changing. Every time I turn around it seems like there’s a new way to build user interfaces on the web. Whether it’s yet another JavaScript framework or a new paradigm like Blazor, there’s always something new. I love the innovation, but I hate having to build new controls for every new platform that comes along.  I would love to avoid this duplicate work.  

As we push the limits of modern web development, web standards also evolve. A new collection of standards, collectively called Web Components, allows us to create reusable components using vanilla JavaScript. We can take those components and use them like any other html tag.  This allows us to simplify our web development while speeding up our applications.  

What’s a web component anyway?

Web components is a term that encompasses three new W3C standards. These three standards give us the ability to create custom elements. 

Custom Elements
The custom elements spec allows you to create new HTML tags that you can add to your page. They behave like any existing HTML Tag. To use this spec, you create a new ES6 class that inherits from an existing element. Then you can define what’s in that custom element and add it to your application as a new tag. 

Shadow DOM
This term used to describe the virtual DOM used in React. Now it referrers to the ability to create an encapsulated DOM tree. This is used in conjunction with the custom elements spec to create components.  

HTML Templates
HTML templates allow you to create snippets of HTML with slots where you can add your own custom markup. This makes it easier to encapsulate boilerplate html and DRY up your code.   

If you want to learn how to make a native web component, my favorite set of tutorials is on the Mozilla Developer Network. 
https://developer.mozilla.org/en-US/docs/Web/Web_Components#Tutorials 

I also built a few simple native web components that you can check out:
https://github.com/DustinEwers/winning-with-web-components/tree/master/basic-components 

What about browser compatibility?

Like most new web standards, web components are not universally supported. Firefox and Edge/IE don’t support web components. To get around this, you can either use a polyfill or a library. Web component libraries make it easier to build components. But, this isn’t like bringing in a big framework. The output of these libraries is still standards compliant web components. It’s like how you use Babel or TypeScript to smooth over old JavaScript. The native web component syntax is a little verbose, so my recommendation is to use a library.  

Polyfills
https://www.webcomponents.org/polyfills 

Libraries, not frameworks…  

There are two popular ones out there. The first, and most popular, is Polymer. Polymer’s goal is to add a layer of syntactic sugar to the existing web components spec. Polymer also includes polyfills that allow you use your components across different web browsers.  If you want to learn more, check out the Polymer Project. 

https://www.polymer-project.org/  

The other library is Stencil.js. Stencil was built by the folks at Ionic. Ionic builds a popular mobile and Progressive Web Application (PWA) framework. Their existing method of using Angular was too slow for a modern PWA. To alleviate this problem, they moved to web components. They also built a library to help them along the way. Stencil makes use of TypeScript and TSX (TypeScript JSX) to build components in a way that feels familiar to folks using React or Angular. It takes the best concepts of Angular and React and combines them together. 

https://stenciljs.com  

If you prefer a more native JavaScript experience and hate helper technologies like TypeScript and JSX, then Polymer is for you. If you like using TypeScript and JSX, Stencil is the library for you. Personally, I like Angular and React, so the syntax in Stencil is appealing to me. Lots of other people agree, but there’s nothing wrong with either library.   

I also have some Stencil demos available. I have a component library and I consume that library from a React application.   

Component Library:
https://github.com/DustinEwers/winning-with-web-components/tree/master/stencil-demo/library

React Application:
https://github.com/DustinEwers/winning-with-web-components/tree/master/react-demo/wc-app

Where Web Components Help You Win

There are a couple of situations where web components are really helpful. The first is when you’re building component library for use in lots of different projects.  This can include your own personal library of components, a core library of components for your company, or set public set of components. Companies that make component libraries, like Ionic or Telerik, have much to gain from web components.   

The second situation is if you want to build a progressive web application. PWAs are rated on their “time to paint”, ie. how fast you can get content to show when you load the application. Applications that rely on frameworks can take up to several seconds to load. Web components load instantaneously. Even in my trivial demo code, there’s a noticeable different in a page built with web components and one built in React.   

As we learn how to do more with web technologies, web standards evolve. Component based frameworks have become the dominant paradigm for building modern web apps. While component based frameworks like React and Angular are great, sometimes you don’t want or need the bulk. Web components combine several standards to build components using native browser technology. To make things easier, you can use libraries like Polymer and Stencil to help you out. Break free of framework churn by using the platform and building web components.   

 

Architecture Patterns for Angular and .NET Core

Modern web application development is fraught with choices. There are many ways to build a modern web application. Some of the choices include: front-end architecture style (SPA, MVC, Razor Pages), front-end framework (React, Angular, jQuery), front-end build tools, CSS pre-processor, JavaScript build tool (Webpack, System.js, Gulp), and back-end architecture. Each of those choices spawns other architectural choices. Depending on what you pick, there could be several dozen decision points in the process. 
 
One of the things I like about Angular is that you don’t need to make as many of these choices. If you use Angular, you don’t have to spend hours searching NPM and Github for the different pieces of your web app. There are still choices to make though. In this post, we’re going to focus on how to integrate your front end (Angular) with your back-end (ASP.NET Core).
 
We are going look at three ways to build a web application. We’ll begin with the time tested monolith. Then we’ll move onto the shiny new “serverless” architecture style. After that, we’ll explore microservices architecture. After this post, you’ll have a good grasp of each of these styles and know when to use each one for your own applications.

Monoliths

If you’ve been building web applications for any amount of time, you’ve probably worked on at least one monolith. In a monolith, the entire application’s workflow is in one code base. In the .NET world, that means everything can fit into one big solution file. Monolith doesn’t mean we can’t have a reasonable separation of code. You can create module boundaries and separate your code into projects. You can even implement an n-teir architecture and separate your application into layers. The key to the monolith is that the whole process is in one self-contained code base.
 
Monolith architecture gets bashed on, but it’s the default for a reason. There’s several advantages to the monolith style. For one, everything is in one place. If you need to refactor, you don’t have to worry about moving across service boundaries. Tools like ReSharper make this even easier. Monoliths are also easy to deploy. If you are building a small or medium sized application, monolith architecture is a good choice.
While monoliths are fine much of the time, there are situations where they tend to fall down. The first problem with monoliths is that they are hard to scale. If you have one piece of an application that’s experiencing a heavier load, you still have to scale out your whole application. Monoliths also deter code reuse. In many corporate environments, there are resources that are used by more than one application. With a monolith, you end up copying the code to access those resources. Because there’s so much code in one place, larger monoliths can be hard to understand. This can make it harder to on-board new team members. Once your application gets to a certain size, you should peel microservices off of your monolith.
 

There are a few ways to implement a monolithic Angular application. The easiest way is to use the built in template. Visual Studio comes with an Angular template that includes some nice features. I prefer to use the Angular CLI, so I don’t use the included template. If you also want to use the Angular CLI, I have a post on how to use Angular CLI with a .NET Core project.

Angular CLI with .NET Core

As I learn more about Angular, I’m beginning to favor another approach. The truth is that .NET doesn’t add much to the Angular front end party. Given a clean slate, I’d run the Angular half of the code as it’s own project and use .NET Core for the API. Angular CLI is perfectly happy self hosting or you can deploy the static assets to an IIS site. 

Serverless

The serverless architecture is the most recent pattern on the list. It’s also the worst named pattern on the list. The servers [obviously] exist, but you don’t have to care about them. It’s “serverless” to you.
 
Serverless architectures rely on services that host and run your code for you. Instead of managing VMs or physical servers, the service abstracts that away. If 500,000 users come knocking on the door to your site, you don’t even need to push up a slider bar. The service scales for you.
 
When people think of serverless, they’re usually thinking about Functions as a Service (FAAS). FAAS platforms allow you to host small bits of code in the cloud. This means a single endpoint. FAAS is not the only way to be serverless though. Services like Firebase can encapsulate the your whole back-end.
 
Here’s a list of serverless platforms: https://github.com/anaibol/awesome-serverless
 
To integrate this with Angular, you compile your Angular application into a static web site. Then you call the APIs you create in whatever serverless service you’re using. This post has details on how to build a serverless Angular application using Azure Functions and an Angular site hosted in an Azure web site. You should be able to adapt these instructions for your favorite cloud provider.
 
Serverless isn’t for every situation, but there’s some definite advantages. The biggest advantage is that you can quickly get your code into production. You don’t need to configure servers or set anything up. You just drop your code into the cloud and go. Server level concerns like scalability and server management are gone. Serverless architectures are also very cheap to start with. FAAS platforms charge you by usage, so low traffic apps are dirt cheap. Static websites are also fast and cheap. Since most static assets are cached, you can serve a ton of users with very little impact.
 
There are a few problems with serverless. The big one for me is complexity. Once you have a certain number of functions, they become hard to manage. I’d rather have a web service or series of web services over a suite of cloud functions. Functions also have somewhat unpredictable pricing. A misconfiguration in your service or a bug can leave you with a huge cloud bill. The serverless pattern really shines when building prototypes and minimum viable products (MVP). You can get code into production and start iterating. Later on, you can refactor your functions into services if your application takes off.

Microservices

The microservices architectural pattern addresses some of the issues found on larger products. Microservices divide the functionality into tightly scoped services. These services are loosely coupled, so you can work on them independently. You can even build them using separate technology stacks.
 
Microservices architecture has several advantages. First, it’s easy to scale microservices. If you have one part of your application that’s receiving lots of traffic, you can scale only that part. Microservices are also easy to understand. Because they are small, it’s easy to drop into a new service and find your way around. Each service is easy to reason about. This is my favorite feature of the microservies architecture. Getting up to speed is much easier than on a big monolith application. Microservices also encourage reuse. In enterprise environments, you often have several applications hitting the same data. With microservices, you can make one service that serves many applications.
 
While microservices are great, there are some drawbacks. The biggest drawback I’ve seen is performance. Because the services are loosely coupled, you use JSON as a commnication mechanism between services. This means you end up doing a lot of serialization and deserialization. Each service boundary you cross incurs an overhead cost. On larger requests, those costs are significant. These service boundaries also make it harder to troubleshoot problems. Tracking down which service in a chain of calls is breaking down can be frustrating.
 
Another pitfall of microservice development is deployment complexity. Even though services are loosely coupled, you still need to manage the dependencies between them when deploying larger features. If you don’t have a good continuous deployment and integration pipeline, you are going to have a bad time.
 
If you want to see a sample microservices and Angular application, I have one here.

Conclusion

Each of the architectures in this post shines in a particular set of circumstances. Monoliths are great for small to medium sized projects, but are not ideal for larger applications. Serverless architecture is great for small apps, but not for large enterprise applications. Microservices architecture works well for large applications, but isn’t worth the overhead on small ones. Figure out the application you want to build and choose wisely. 

Angular CLI With .NET Core

Update February 2018

The fine folks at Microsoft now have a template that integrates Angular CLI and .NET Core. I used it on my last Angular project and found it to be quite useful. One thing they missed is that the polyfills for Internet Explorer are not enabled by default, so you’ll want to go to polyfills.ts and enable those.

Check it out here.

If you’re still interested in how to do this manually, continue on.


Angular is a fantastic platform for building rich client side apps, but let’s not forget about the back end. My choice for the back end is ASP.NET Core. If you’re not shy about spending a bunch of time setting up Webpack, Angular and ASP.NET Core is a fantastic combination.

However, I prefer to spend my time building applications, not configuring build tools. Angular CLI takes a lot of the pain out of using Angular, but it’s a self contained command line tool. Fortunately, Angular CLI and ASP.NET Core can happily co-exist. In this post, we’re going to build an application using these two technologies together. By the end, you’ll be ready to have all the goodness of Angular and ASP.NET Core without spending a week setting up Webpack.

Prerequisites

Make sure you have .NET Core, Node.js and Angular CLI installed.

https://www.microsoft.com/net/core#windowsvs2017

https://nodejs.org/en/

npm install -g @angular/cli 

Getting Started: ASP.NET Core App Setup

Fire up Visual Studio (I’m using VS 2017) and create a new ASP.NET Core Web Application. Select the Web API Starter. This doesn’t bring in any web stuff, which is ideal. We’re going to use Angular CLI to generate the client files.

Then go ahead and disable automatic Typescript compilation. We want CLI to compile our Typescript, not Visual Studio. Do this by adding the “TypeScriptCompilerBlocked” line to your csproj file.

Head on over to the Startup.cs and add in the static files middleware. You’ll have to install the “Microsoft.AspNetCore.StaticFiles” NuGet package. After that, add app.UseDefaultFiles() and app.UseStaticFiles() to your Configure() method.

After you get those setup, you’ll want to add some middleware to redirect those pesky 404s to the root file. This will allow you to navigate the application without having to start at the root each time you hit refresh. For this app, api routes are prefixed with “api”, so we’re excluding those routes from the check. We’re also excluding routes with a file extension since those are likely static assets.

To prevent the app from loading up the api/values endpoint by default, go to properties/launchSettings.json and change the “launchUrl” keys from “api/values” to “”.

At this point, our .NET Core app should be ready to go. Let’s move on to the Angular code.

Setting Up Angular CLI

We’re going generate our Angular app on top of our ASP.NET core app. To do this, go to the command line and navigate to the directory of your solution file. Then run “ng new <your app name>”.

You want the <app name> part to be the same as your .NET Core source folder. This will drop all of the CLI files into your ASP.NET Core root folder. It should look like this:

Gluing It All Together

Angular has a default file structure, but it’s not ideal for the existing ASP.NET Core application. Fortunately, Angular CLI has some options that will allow us to change this structure. We want the client side code to be in a folder called “client-src” and the client side build artifacts to go to the wwwroot folder. To do this, rename the “src” folder to “client-src”. Then go to go to .angular-cli.json. This is the primary configuration file for Angular CLI. First, change “src” to “client-src”. Then change the “outDir” attribute from “dist” to “wwwroot”. This will drop all of the compiled assets into the wwwroot folder.

At this point, we can build the Angular application using Angular CLI. Navigate a command prompt into the main application folder and run “ng build”. This command will build the client side part of the application, dropping the build artifacts into wwwroot. The wwwroot folder should look like this:

  

At this point we should be able to run the app by hitting the Run button in Visual Studio. Unfortunately, we still have a two stage build pipeline. The first step being “ng build” to generate the client side files and then running the .NET Core app. To fix this, we can drop in a post build script: “ng build — aot”. This will compile the client side files (with ahead of time compiling) after the app builds.

Bonus Points

If you’re using git, you’ll want to add the wwwroot folder to your .gitignore file. These files are generated, so you probably don’t want to check them in.

Example Code

All of the demo code used in this post is available here:

https://github.com/DustinEwers/shiny-angular-demos/tree/master/ninjas-quest-cli-core/ninjas-quest

This demo includes a full Angular application on top of ASP.NET core. Feel free to use this as a template or something to look at while building your own. You now have everything you need to get started building shiny applications using Angular CLI and ASP.NET Core.

Cutting Through The JavaScript Toolchain Thicket with Angular CLI

If there is a developer hell, one of the circles will involve the JavaScript toolchain. The JavaScript ecosystem is awash in tools, choices, and configuration options. Combine that with spurious documentation and constant change and you have a jungle of pain awaiting any brave soul who dares build a modern JS application.

Much has been done to ease JavaScript toolchain fatigue. There are templates and starter packs for most of the popular JS stacks. If you’re using Angular 2, the Angular team has created a tool called Angular CLI. It encapsulates all the best practices into one handy command line tool. Angular CLI shortcuts most of the Angular 2 setup. Just run a few commands and you have a working application. In addition to the build tools, you also get a set of scaffolding tools. If you’re familiar with the Ruby on Rails scaffolding tools, Angular CLI will feel right at home. In the interest of trying new things, I decided to kick the tires on Angular CLI and see if it lives up to the hype. I took my demo Angular 2/TypeScript/Webpack application (repo here) and ported it over to Angular CLI.

Installing Angular CLI

npm install -g angular-cli

Install the Angular CLI tool using NPM. Make sure to run the npm install as an administrator. Easy peasy.

Scaffolding an Application

npm install -g angular-cli
ng new <my app name>
cd <my app name>
ng serve

These commands will spin up a basic app structure for you to use. This app structure has a lot of goodies included. Testing, linting, hot module loading, and a decent starter app all come with the basic template. CLI abstracts away the webpack setup, so you don’t have to figure that out. It even includes a basic demo server for you to serve your application from. The only thing that the angular cli doesn’t include is a style library. I’d love to see Angular Material or Bootstrap included with the CLI, but I’ll live.

Here’s what comes out of the box with a new Angular CLI Project:

I was curious about how up to date the basic setup is, so I ran “npm outdated”. NPM packages change often. It looks like most of the packages are close to their most recent version, but the CLI used Angular 2.3 instead of Angular 2.4.

Generators

Boilerplate code sucks and Angular 2 has a bunch of it. There are lots of small files that need be built when you add a new component. Angular CLI has generators to help with that. I tried out a few of the generators. I found the component generator to be particularly useful. It builds out the template, code, and spec files. It also adds the component to its root module. This is a great time saver. The route generator was far less useful, however, as it didn’t do anything. It looks like they’re going to add it back in later.

Styles

The default template doesn’t include any style libraries, so I pulled in Angular Material (currently in beta).

To install:

npm install --save @angular/material

Then you need to pull it into your app module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { CharacterBuilderComponent } from './character-builder/character-builder.component';
import { EncounterComponent } from './encounter/encounter.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { StatsComponent } from './stats/stats.component';
import { HomeComponent } from './home/home.component';
import { MaterialModule } from '@angular/material';
@NgModule({
declarations: [
AppComponent,
CharacterBuilderComponent,
EncounterComponent,
NavMenuComponent,
StatsComponent,
HomeComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MaterialModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Finally, add a theme file to your site.css. There are several pre-built themes, but you can make your own if you want.

@import '~@angular/material/core/theming/prebuilt/deeppurple-amber.css';

After importing the styles I ported all of my demo code over into the angular cli project. This process was surprisingly easy. Unfortunately, the Material styles are not as robust as the Bootstrap styles. I’m sure I made a mistake somewhere, but I wasn’t really going for maximum style, so I let it go. I’m looking forward to Material UI being ready for primetime, but I don’t think it’s quite there yet.

Final Verdict

I wouldn’t use Angular CLI in production (yet), but I think it’s a fantastic tool for playing with and learning Angular 2. It takes the most painful part of setting up an Angular 2 project and makes it a breeze. You can get up and going faster than building an environment from scratch. I’m going to keep an eye on this project and see how it develops. If you build Angular 2 apps, I recommend you do the same.

Here’s the final result:

https://github.com/DustinEwers/typescript-demos/tree/master/ts-demo-node/ninjas-quest

How to Turn Off TypeScript Automatic Compilation in Visual Studio

TypeScript is a first class citizen in the Visual Studio universe. By default, Visual Studio will compile your typescript files whenever you save them. This is great for many types of TypeScript projects, unless you’re using a tool like Webpack or Gulp. These tools handle TypeScript compilation by themselves. You don’t want Visual Studio to waste your time generating spurious files. Fortunately, it’s easy to disable automatic TypeScript compilation. Just add a “TypeScriptCompileBlocked” element to your project’s xproj file and give it a value of “True”. This will prevent Visual Studio from making those pesky extra files.

Set the TypeScriptCompiledBlocked to True in the Xproj file

Disabling automatic TypeScript Compilation