ASP.NET Core + TypeScript

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)
  • Search for .NET Core in the project search bar
  • Select ASP.NET Core Web Application and press the Next buttonASP.NET Core - 图1

  • Name your project and solution. After select the Create buttonASP.NET Core - 图2

  • In the last window, select the Empty template and press the Create buttonASP.NET Core - 图3

Run the application and make sure that it works.

ASP.NET Core - 图4

Set up the server

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

ASP.NET Core - 图5

Open up your Startup.cs file and edit your Configure function to look like this:

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseDeveloperExceptionPage();
  6. }
  7. app.UseDefaultFiles();
  8. app.UseStaticFiles();
  9. }

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

Add TypeScript

Next we will add a new folder and call it scripts.

ASP.NET Core - 图6

ASP.NET Core - 图7

Add TypeScript code

Right click on scripts and click New Item. Then choose TypeScript File and name the file app.ts

ASP.NET Core - 图8

Add example code

Add the following code to the app.ts file.

  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 scripts and click New Item. Then choose TypeScript Configuration File and use the default name of tsconfig.json

ASP.NET Core - 图9

Replace the contents of the tsconfig.json file with:

  1. {
  2. "compilerOptions": {
  3. "noEmitOnError": true,
  4. "noImplicitAny": true,
  5. "sourceMap": true,
  6. "target": "es6"
  7. },
  8. "files": [
  9. "./app.ts"
  10. ],
  11. "compileOnSave": true
  12. }
  • onEmitOnError : Do not emit outputs if any errors were reported.
  • noImplicitAny : Raise error on expressions and declarations with an implied any type.
  • sourceMap : Generates corresponding .map file.
  • target : Specify ECMAScript target version.

Note: "ESNext" targets latest supported

"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 #

We need to setup NPM so that JavaScript packages can be downloaded. Right click on the project and select New Item. Then choose NPM Configuration File and use the default name of package.json.

ASP.NET Core - 图10

Inside the "devDependencies" section of the package.json file, add gulp and del

  1. "devDependencies": {
  2. "gulp": "4.0.2",
  3. "del": "5.1.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.

After you should see an npm folder in your solution explorer

ASP.NET Core - 图11

Set up gulp #

Right click on the project and click New Item. Then choose JavaScript File and use the name of gulpfile.js

  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.

ASP.NET Core - 图12

If ‘default’ and ‘clean’ tasks don’t show up, refresh the explorer:

ASP.NET Core - 图13

Write a HTML page

Right click on the wwwroot folder (if you don’t see the folder try building the project) and add a New Item named index.html inside. 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
  • As you type on the boxes you should see the message appear/change!ASP.NET Core - 图14

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.ASP.NET Core - 图15

Congrats you’ve built your own .NET Core project with a TypeScript frontend.