Setup

Install ASP.NET Core and TypeScript

First, install ASP.NET Core if you need it. This quick-start guide requires Visual Studio 2015 or 2017.

Next, if your version of Visual Studio does not already have the latest TypeScript, you can install it.

Create a new project

  • Choose File
  • Choose New Project (Ctrl + Shift + N)
  • Choose Visual C#
  • For VS2015, choose ASP.NET Web Application > ASP.NET 5 Empty, and let’s uncheck “Host in the cloud” since we’re going to run this locally.

Use empty template

For VS2017, choose ASP.NET Core Web Application (.NET Core) > ASP.NET Core 1.1 Empty instead.

Use empty template VS2017

Run the application and make sure that it works.

Set up the server

VS2015

In project.json add another entry in "dependencies":

  1. "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"

The resulting dependencies should look like this:

  1. "dependencies": {
  2. "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
  3. "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
  4. "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"
  5. },

Replace the body of Configure in Startup.cs with

  1. public void Configure(IApplicationBuilder app)
  2. {
  3. app.UseIISPlatformHandler();
  4. app.UseDefaultFiles();
  5. app.UseStaticFiles();
  6. }

VS2017

Open Dependencies > Manage NuGet Packages > Browse. Search and install Microsoft.AspNetCore.StaticFiles 1.1.2:

Install Microsoft.AspNetCore.StaticFiles

Replace the body of Configure in Startup.cs with

  1. public void Configure(IApplicationBuilder app)
  2. {
  3. app.UseDefaultFiles();
  4. app.UseStaticFiles();
  5. }

You may need to restart VS for the red squiggly lines below UseDefaultFiles and UseStaticFiles to disappear.

Add TypeScript

The next step is to add a folder for TypeScript.

Create new folder

We’ll just call it scripts.

scripts folder

Add TypeScript code

Right click on scripts and click New Item.Then choose TypeScript File (it may be in the .NET Core section) and name the file app.ts.

New item

Add example code

Type the following code into app.ts.

  1. function sayHello() {
  2. const compiler = (document.getElementById("compiler") as HTMLInputElement).value;
  3. const framework = (document.getElementById("framework") as HTMLInputElement).value;
  4. return `Hello from ${compiler} and ${framework}!`;
  5. }

Set up the build

Configure the TypeScript compiler

First we need to tell TypeScript how to build.Right click on the scripts folder and click New Item.Then choose TypeScript Configuration File and use the default name tsconfig.json.

Create tsconfig.json

Replace the default tsconfig.json with the following:

  1. {
  2. "compilerOptions": {
  3. "noImplicitAny": true,
  4. "noEmitOnError": true,
  5. "sourceMap": true,
  6. "target": "es5"
  7. },
  8. "files": [
  9. "./app.ts"
  10. ],
  11. "compileOnSave": true
  12. }

This is similar to the default, with the following differences:

  • It sets "noImplicitAny": true.
  • It explicitly lists "files" instead of relying on "excludes".
  • It sets "compileOnSave": true. "noImplicitAny" is good idea whenever you’re writing new code — you can make sure that you don’t write any untyped code by mistake."compileOnSave" makes it easy to update your code in a running web app.

Set up NPM

Now we need to set up NPM so we can download JavaScript packages.Right click on the project and click New Item.Then choose NPM Configuration File and use the default name package.json.Inside "devDependencies" add “gulp” and “del”:

  1. "devDependencies": {
  2. "gulp": "3.9.0",
  3. "del": "2.2.0"
  4. }

Visual Studio should start installing gulp and del as soon as you save the file.If not, right-click package.json and then Restore Packages.

Set up gulp

Finally, add a new JavaScript file named gulpfile.js.Put the following code inside:

  1. /// <binding AfterBuild='default' Clean='clean' />
  2. /*
  3. This file is the main entry point for defining Gulp tasks and using Gulp plugins.
  4. Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
  5. */
  6. var gulp = require('gulp');
  7. var del = require('del');
  8. var paths = {
  9. scripts: ['scripts/**/*.js', 'scripts/**/*.ts', 'scripts/**/*.map'],
  10. };
  11. gulp.task('clean', function () {
  12. return del(['wwwroot/scripts/**/*']);
  13. });
  14. gulp.task('default', function () {
  15. gulp.src(paths.scripts).pipe(gulp.dest('wwwroot/scripts'))
  16. });

The first line tells Visual Studio to run the task ‘default’ after the build finishes.It will also run the ‘clean’ task when you ask Visual Studio to clean the build.

Now right-click on gulpfile.js and click Task Runner Explorer.If ‘default’ and ‘clean’ tasks don’t show up, refresh the explorer:

Refresh Task Runner Explorer

Write an HTML page

Add a New Item named index.html inside wwwroot.Use the following code for index.html:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <script src="scripts/app.js"></script>
  6. <title></title>
  7. </head>
  8. <body>
  9. <div id="message"></div>
  10. <div>
  11. Compiler: <input id="compiler" value="TypeScript" onkeyup="document.getElementById('message').innerText = sayHello()" /><br />
  12. Framework: <input id="framework" value="ASP.NET" onkeyup="document.getElementById('message').innerText = sayHello()" />
  13. </div>
  14. </body>
  15. </html>

Test

  • Run the project.
  • You should see a message when you type in the input boxes: Picture of running demo

Debug

  • In Edge, press F12 and click the Debugger tab.
  • Look in the first localhost folder, then scripts/app.ts
  • Put a breakpoint on the line with return.
  • Type in the boxes and confirm that the breakpoint hits in TypeScript code and that inspection works correctly. Demo paused on breakpoint

That’s all you need to know to include basic TypeScript in your ASP.NET project.Next we’ll include Angular and write a simple Angular app.

Add Angular 2

Add NPM dependencies

Add Angular 2 and SystemJS to dependencies in package.json.

For VS2015, the new dependencies list:

  1. "dependencies": {
  2. "angular2": "2.0.0-beta.11",
  3. "systemjs": "0.19.24",
  4. "gulp": "3.9.0",
  5. "del": "2.2.0"
  6. },

For VS2017, due to the deprecation of peer dependencies in NPM3, we need to list Angular 2’s peer dependencies directly as dependencies as well:

  1. "dependencies": {
  2. "angular2": "2.0.0-beta.11",
  3. "reflect-metadata": "0.1.2",
  4. "rxjs": "5.0.0-beta.2",
  5. "zone.js": "^0.6.4",
  6. "systemjs": "0.19.24",
  7. "gulp": "3.9.0",
  8. "del": "2.2.0"
  9. },

Update tsconfig.json

Now that Angular 2 and its dependencies are installed, we need to enable TypeScript’s experimental support for decorators.We also need to add declarations for ES2015, since Angular uses core-js for things like Promise.In the future decorators will be the default and these settings will not be needed.

Add "experimentalDecorators": true, "emitDecoratorMetadata": true to the "compilerOptions" section.Next, add "lib": ["es2015", "es5", "dom"] to "compilerOptions" as well to bring in declarations from ES2015.Finally, we’ll need to add a new entry in "files" for another file, "./model.ts", which we’ll create.Our tsconfig should now look like this:

  1. {
  2. "compilerOptions": {
  3. "noImplicitAny": true,
  4. "noEmitOnError": true,
  5. "sourceMap": true,
  6. "experimentalDecorators": true,
  7. "emitDecoratorMetadata": true,
  8. "target": "es5",
  9. "lib": [
  10. "es2015", "es5", "dom"
  11. ]
  12. },
  13. "files": [
  14. "./app.ts",
  15. "./model.ts",
  16. "./main.ts"
  17. ],
  18. "compileOnSave": true
  19. }

Add Angular to the gulp build

Finally, we need to make sure that the Angular files are copied as part of the build.We need to add:

  • The paths to the library files.
  • Add a lib task to pipe the files to wwwroot.
  • Add a dependency on lib to the default task. The updated gulpfile.js should look like this:
  1. /// <binding AfterBuild='default' Clean='clean' />
  2. /*
  3. This file is the main entry point for defining Gulp tasks and using Gulp plugins.
  4. Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
  5. */
  6. var gulp = require('gulp');
  7. var del = require('del');
  8. var paths = {
  9. scripts: ['scripts/**/*.js', 'scripts/**/*.ts', 'scripts/**/*.map'],
  10. libs: ['node_modules/angular2/bundles/angular2.js',
  11. 'node_modules/angular2/bundles/angular2-polyfills.js',
  12. 'node_modules/systemjs/dist/system.src.js',
  13. 'node_modules/rxjs/bundles/Rx.js']
  14. };
  15. gulp.task('lib', function () {
  16. gulp.src(paths.libs).pipe(gulp.dest('wwwroot/scripts/lib'));
  17. });
  18. gulp.task('clean', function () {
  19. return del(['wwwroot/scripts/**/*']);
  20. });
  21. gulp.task('default', ['lib'], function () {
  22. gulp.src(paths.scripts).pipe(gulp.dest('wwwroot/scripts'));
  23. });

Again, make sure that Task Runner Explorer sees the new lib task after you save the gulpfile.

Write a simple Angular app in TypeScript

First, change the code in app.ts to:

  1. import {Component} from "angular2/core"
  2. import {MyModel} from "./model"
  3. @Component({
  4. selector: `my-app`,
  5. template: `<div>Hello from {{getCompiler()}}</div>`
  6. })
  7. export class MyApp {
  8. model = new MyModel();
  9. getCompiler() {
  10. return this.model.compiler;
  11. }
  12. }

Then add another TypeScript file in scripts named model.ts:

  1. export class MyModel {
  2. compiler = "TypeScript";
  3. }

And then another TypeScript file in scripts named main.ts:

  1. import {bootstrap} from "angular2/platform/browser";
  2. import {MyApp} from "./app";
  3. bootstrap(MyApp);

Finally, change the code in index.html to the following:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <script src="scripts/lib/angular2-polyfills.js"></script>
  6. <script src="scripts/lib/system.src.js"></script>
  7. <script src="scripts/lib/rx.js"></script>
  8. <script src="scripts/lib/angular2.js"></script>
  9. <script>
  10. System.config({
  11. packages: {
  12. 'scripts': {
  13. format: 'cjs',
  14. defaultExtension: 'js'
  15. }
  16. }
  17. });
  18. System.import('scripts/main').then(null, console.error.bind(console));
  19. </script>
  20. <title></title>
  21. </head>
  22. <body>
  23. <my-app>Loading...</my-app>
  24. </body>
  25. </html>

This loads the app.When you run the ASP.NET application you should see a div that says “Loading…” and then updates to say “Hello from TypeScript”.