March 7, 2016

Getting started with TypeScript in ASP.Net MVC Project

Microsoft introduced TypeScript, a typed superset for ECMAScript 2015 (ES2015) syntax that compiles down into plain JavaScript, it provides the ability to translate/compile its features into ECMAScript 3 or 5. Since JavaScript is just a scripting language and not have designed as a programming language for big web applications. It does not provide structured coding pillars likes classes, interfaces, modules/namespaces. So there comes TypeScript, both language and compiler is open-sourced under Apache 2.0 license. TypeScript compiler performs only file-local transformations for TypeScript code files, and does not re-order the code segments (like variable declarations).

It focuses on providing useful tools for building large scale applications by implementing features, such as classes, interfaces, OOPs, modules and much more. TypeScript file extension is .ts and when compiled, it produces plain JavaScript output file with .js extension. In this tutorial, we will try to get started with TypeScript in Visual Studio IDE, by first installing its plugin for Visual Studio and then will write small TypeScript code to make sure we have installed TypeScript successfully and ready to write real code for our applications.

There are two main ways to install the TypeScript

Since we are using Visual Studio as our IDE, I will follow second option in this post. Now I assumed that you have Visual Studio setup with required TypeScript plugin and also Web Essentials. Create a sample ASP.Net MVC Web Application project, and run it to see every thing is working fine.

Incorporate TypeScript into Visual Studio projects

Lets add our first TypeScript in this project, create a new file with FileTemplate as TypeScript File, named file1.ts, all typescript files have extension of .ts. When you compiled project next time, if every thing is properly setup it will be build successfully. But you might not get the generated output javascript file, if so, you might have to follow these instructions.

First right click on project file in Solution Explorer, and click Unload Project.

Right click on project file in Solution Explorer, and click Edit {ProjectName}.csproj.

In xml, look for ItemGroup tags, and add a new ItemGroup tag for typescript files we want to use. So in this example, since we only have one typescipt file file1.ts, you should have something similar to this.


     <ItemGroup>
    <Content Include="file.js">
      <DependentUpon>file.ts</DependentUpon>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <TypeScriptCompile Include="file1.ts" />
  </ItemGroup>
  <Target Name="BeforeBuild">
    <Exec Command="&quot;$(PROGRAMFILES)\Microsoft SDKs\TypeScript\0.8.0.0\tsc&quot;@(TypeScriptCompile ->'"%fullpath)"', ' ')" />
  </Target>

After finished adding support for typescript files in project file's xml, right click on the project file and click Reload Project.

Try rebuild the project, it should be completed successfully.

Now our project is ready for typescript. Remember that typescript is only syntactic sugar, and has value only till compile time. On successfully compilation, it generates the output javascript file or real use in the same directory where current typescript file is placed. So it means, finally you have to use the generated javascript file in html as we are using regular javascript. Lets see typescript in action.

Open BundleConfig class in App_Start folder, and add the generated javascript file path in RegisterBundles function as follows:

 public static void RegisterBundles(BundleCollection bundles)
 {
  ...code removed for clearity 

  bundles.Add(new ScriptBundle("~/bundles/MyJavaScript").Include(
        "~/MyTypeScripts/file1.js"
        ));
 }

We have to add the file path for generated javascript file, not the typescript file. For this example, I am adding a simple button in Index view of HomeController. But before this you have to add the script reference in shared _Layout.cshtml in head section:

    @Scripts.Render("~/bundles/MyJavaScript")
At the bottom of the Index view of HomeController, I added the following script tag:
    // A $( document ).ready() block.
    $(document).ready(function () {

        initMyScript();
    });

This will call initMyScript() javascript function on document load. So far we have not written this function in javascript or typescript. Lets write first typescript code in file.ts. Since this post is limited only for getting started typescript in Visual Studio, so I used only simple script for clarity.

function initMyScript(): void {

    document.getElementById("aLink").addEventListener("click", setParagraphText);
}

function setParagraphText():void {

    var msg: string = "link is clicked";
    document.getElementById("pTest").innerHTML = msg;
}

This typescript defines two functions, initMyScript() function, which is called on document load, and attach an event listener for click event of element aLink. The setParagraphText() event handler sets the innerHTML of element pTest by a simple string variable.

One successfully compilation of above typescript, it will generate the corresponding javascript in file.js:

function initMyScript() {
    document.getElementById("aLink").addEventListener("click", setParagraphText);
}
function setParagraphText() {
    var msg = "link is clicked2";
    document.getElementById("pTest").innerHTML = msg;
}
//# sourceMappingURL=file1.js.map
And this is simple html for elements used in above script:
<div class="col-md-4">
        <p><a id="aLink" class="btn btn-default" >Click Me</a></p>

        <p id="pTest">This content will be replaced.</p>
</div>

Thats it. Now run your project to see TypeScript in action. I discussed here only the minimum steps required to incorporate TypeScript in Visual Studio MVC Projects. You can continue playing with TypeScript by adding advanced features.

References:

http://www.typescriptlang.org

5 comments:

  1. Nice blog on how Getting started with TypeScript in ASP.Net MVC Project. Here it describes step by step graphically and pictorially. Really useful for asp.net user and developer. Developing a website for personal or professional use is a very good idea and hosting is necessary for a website. So you have to Find The service provider that offers the best asp.net hosting.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete