Angular 2 + ASP.NET Core QuickStart using Visual Studio Code

I’ve been using Angular 2 and ASP.NET Core to build single page applications and there is so much that needs to be done before you even start! To ease the pain, I’ve created a simple quickstart application that can be used as a starter project for new applications. You can download the source code now, or follow the instructions below to build the quickstart from scratch.

Before we begin you’ll need to make sure your development environment is set up correctly including:

  • Node.js and npm
  • TypeScript
  • Visual Studio Code
  • ASP.NET Core (formally known as ASP.NET 5)

If you don’t meet these prerequisites follow this guide to set up Node.js, npm, TypeScript, and Visual Studio Code. Then follow this guide to set up ASP.NET Core.

In addition, you should already understand the basics of Angular 2 and ASP.NET Core. For more information, see:

Scaffold a new ASP.NET Core application

Using the full version Visual Studio, we would typically create a new application using File | New Project. We can’t do that with Visual Studio Code so instead we’ll scaffold a new application using Yeoman – the web’s scaffolding tool for modern webapps.

Yeoman and the Yeoman generator for ASP.NET Core apps can be installed using the node package manager (npm) with the following command (be sure to run as administrator):

    npm install -g yo generator-aspnet

Now that we have Yeoman installed we can scaffold a new ASP.NET Core application. Navigate to your projects folder (e.g. c:\code) and execute the following command:

    yo aspnet

Use the arrow keys to select Web API Application and specify ng2-aspnetcore-quickstart as the application name.

Now that the project is created, the first thing we need to do is restore the required NuGet packages listed in project.json. To do so, execute the following commands:

    cd ng2-aspnetcore-quickstart
    dnu restore

Before continuing take a moment to review the generated code. You can launch Visual Studio Code with the following command:

    code .

Configure TypeScript

We need to configure TypeScript, enable intellisense, and enable transpiling (translate TypeScript into JavaScript). Using Visual Studio Code, create a new tsconfig.json file inside the project folder as follows:

{
    "compilerOptions": {
        "target": "es5",
        "module": "system",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
    },
    "exclude": [
        "node_modules",
        "typings/main",
        "typings/main.d.ts"
    ]
}

The tsconfig.json file defines the settings for TypeScript.

Next, within the project folder, create a new typings.json file as follows:

{
    "ambientDependencies": {
        "es6-shim": "registry:dt/es6-shim#0.31.2+20160317120654",
        "jasmine": "registry:dt/jasmine#2.2.0+20160412134438"
    }
}

This file provides intellisense for the specified dependencies through the use of type definition (.d.ts) files.

Lastly, create a task for transpiling TypeScript files:

  1. Press F1
  2. Type Tasks
  3. Select Tasks: Configure Task Runner…
  4. Select TypeScript – Watch Mode

Within the .vscode folder, a new tasks.json file will be created containing a tsc task. Running this task will transpile all existing .ts files, and then continue to monitor them for changes (automatically transpiling as necessary).

Configure and install client dependencies

We will use npm to manage our client dependencies. Within the project folder, create a new package.json file as follows:

{
  "name": "ng2-aspnetcore-quickstart",
  "version": "1.0.0",
  "license": "ISC",
  "scripts": {
    "postinstall": "typings install"
  },
  "dependencies": {
    "@angular/common": "2.0.0-rc.1",
    "@angular/compiler": "2.0.0-rc.1",
    "@angular/core": "2.0.0-rc.1",
    "@angular/http": "2.0.0-rc.1",
    "@angular/platform-browser": "2.0.0-rc.1",
    "@angular/platform-browser-dynamic": "2.0.0-rc.1",
    "@angular/router": "2.0.0-rc.1",
    "@angular/router-deprecated": "2.0.0-rc.1",
    "@angular/upgrade": "2.0.0-rc.1",
    "systemjs": "0.19.27",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "typescript": "1.8.10",
    "typings": "^0.8.1"
  }
}

This file specifies the packages our project depends on, including Angular 2, TypeScript, Bootstrap, and so on.

Within the command prompt navigate to the project folder (e.g. c:\code\ng2-aspnetcore-quickstart) and execute the following command:

    npm install

This will download the client dependencies specified in package.json, and then it will download the TypeScript definition files as specified in typings.json.

Configuring ASP.NET Core

Next we need to configure ASP.NET Core so that we can support default files (e.g. index.html) and allow access to the node_modules folder from the client (by default only the wwwroot folder is accessible).

Within the project folder, open Startup.cs, and add the following using statements:

using System.IO;
using Microsoft.AspNet.FileProviders;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Extensions.PlatformAbstractions;

Then change the Configure method as follows:

public void Configure(IApplicationBuilder app, IApplicationEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    app.UseIISPlatformHandler();
    app.UseDefaultFiles();
    app.UseStaticFiles();
    var nodePath = Path.Combine(env.ApplicationBasePath, "node_modules");
    app.UseFileServer(new FileServerOptions()
    {
        FileProvider = new PhysicalFileProvider(nodePath),
        RequestPath = "/node_modules",
        EnableDirectoryBrowsing = true
    });
    app.UseMvc();
}

Completing the application

The application is now fully configured and you could start coding. However for the purposes of this guide we’ll finish by adding in the Angular 2 QuickStart files from angular.io.

Within wwwroot, create a new systemjs.config.js file as follows:

(function(global) {

  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    'rxjs':                       'node_modules/rxjs',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    '@angular':                   'node_modules/@angular'
  };

  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
  };

  var packageNames = [
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/router-deprecated',
    '@angular/testing',
    '@angular/upgrade',
  ];

  // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
  packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
  });

  var config = {
    map: map,
    packages: packages
  }

  // filterSystemConfig - index.html's chance to modify config before we register it.
  if (global.filterSystemConfig) { global.filterSystemConfig(config); }

  System.config(config);

})(this);

Next, still within wwwroot, create an index.html file as follows:

  
    
    
    
    

    
     
    

    
    
    

    
    
    
  

  
  
    Loading...
  

Again within wwwroot, create a styles.css file as follows:

/* Master Styles */
h1 {
  color: #369; 
  font-family: Arial, Helvetica, sans-serif;   
  font-size: 250%;
}
h2, h3 { 
  color: #444;
  font-family: Arial, Helvetica, sans-serif;   
  font-weight: lighter;
}
body { 
  margin: 2em; 
}
body, input[text], button { 
  color: #888; 
  font-family: Cambria, Georgia; 
}

Now for the Angular 2 components. Under wwwroot create a new app folder, and within the app folder, create a main.ts file as follows:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';

bootstrap(AppComponent);

And finally, under the app folder, create a app.component.ts file as follows:

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: '

Angular 2 + ASP.NET Core QuickStart

'
})
export class AppComponent { }

Building and Running the Application

We’re done! Within Visual Studio Code build the application using Ctrl + Shift + B. Then within a command prompt run the application using dnx web.

When you navigate to http://localhost:5000/ you should see the message Angular 2 + ASP.NET Core QuickStart. If not, take a look at the source code to see where you went wrong.

I hope you’ve found this guide useful. Feel free to reply with any questions, comments, or improvements.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] a year ago I created the Angular 2 + ASP.NET Core QuickStart using Visual Studio Code. In that quickstart I used the Yeoman generator for ASP.NET core apps to scaffold base the ASP.NET […]