Friday, September 30, 2016

Ensuring TypeScript Files Are Served to the Browser for Debugging Using ASP.NET Core

I'm working on an ASP.NET Core site that's an Angular + TypeScript app leveraging all of the goodies in the new web template including the use of a task runner like Gulp. As I'm running my site I wanted to debug my TypeScript files in the Chrome debugger, but upon selecting the file it appeared blank. The .js files appeared correctly, but not the TypeScript files. There are just a few steps to follow to get the all the needed files to load into the browser properly.

1. Update startup.cs Configuration

Ensure the ASP.NET core application is set to serve up static files. To do this, configure the middleware to enable static files to be served to wwwroot. This makes wwwroot servable. You should also depending on the site your creating have the middleware configured to serve up a default home page to your base URL. Odds are you already had both of these steps complete or your site wouldn't even work, but to be thorough make sure you have the following in startup.cs:


2. Update tsconfig.json

If you are using tsconfig.json as well as a task runner like a gulp file, then you are probably leveraging tsconfig to build and transpile the TypeScript files and gulp to deploy them. If this is how you have your application setup, then you'll want to ensure that the sourcemap (.js.map) files are also generated. This will generate the .map files and add the proper reference at the bottom of the .js file to the corresponding map file. These map files let the debugger map between the emitted JavaScript code and the TypeScript files it was transpiled from originally. The .map reference will look like the following (you don't have to add this manually - it's just for reference):


In order to create the map file, make sure the following setting is in your tsconfig.json file and set to 'true':


3. Update gulp.js tasks

The last step is to ensure that the TypeScript files are copied out to your deployment target (i.e. wwwroot). Typically using gulp you'd have both development and release configurations. Ensure that for your dev settings or for whenever you want to debug TypeScript (.ts) files, you add a command to also copy out the TypeScript files as well. Normally only the .js files are needed by the browser, so often we'll overlook copying out the TypeScript files, but this is important so the browser has access and can display them correctly.


That should do it - now when you open the Chrome debugger and click on a TypeScript file it should load properly.