Category Archives for TypeScript

Angular CLI With .NET Core

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