Sunday, July 3, 2016

Building a web application using ASP.NET Core 1.0, Aurelia, TypeScript, Webpack in Visual Studio Code – Part 2

Introduction

YouTube Video Link for Part 2:

This is the second part of Building a web application using ASP.NET Core 1.0, Aurelia, TypeScript, Webpack in Visual Studio Code.

The source code for this tutorial is available on GitHub.

In Part 1 of this series, we setup a ASP.NET Core project with simple Mvc and WebApi Controllers. In this part, we’ll focus on setting up the client side tools and frameworks required to build a modern web application. Let us get started.

Prerequisites

Please create a new folder named “part2” under “C:\tutorial” and copy the contents of “C:\tutorial\part1\modern” into “C:\tutorial\part2\modern”. If you are familiar with git and use github, you can pull the source code from my github repository: https://github.com/rajajhansi/aspnetcore-aurelia-tutorial . After you got the source code, delete the “.git” directory before you copy the contents into “C:\tutorial\part2\modern”.

TypeScript

I’ve chosen TypeScript, which is a super set of ECMAScript as the choice for developing client side code. VS Code has very good support for building TypeScript applications. Since TypeScript uses the features in ES2015 (ES6) and ES2016 (ES7) specifications, code written in TypeScript must be converted to ES5, which is the version that is supported on all browsers. Although a subset of ES6 features are available in Chrome, Edge and Firefox, modules and module loaders are not yet implemented natively. The conversion process from TypeScript or ES6/7 to ES5 is known as transpiling. Babel is a very popular transpiler out there.

Since TypeScript is all about types and type checking during transpile time, we need type definitions of popular JS libraries like jQuery, momentjs etc. Luckily, all modern and new JS frameworks like Aurelia, Angular2, React etc., ships the type definition files. Type definition files use the convention <name>.d.ts. We can download the typings of popular JS libraries using a tool named “typings”.

NPM

There are quite a few package managers out there but my choice is NPM because it hosts both server and client side frameworks. For .NET Core, we’ll still be using Nuget package manager. But, for the client side, I don’t want to use bower, jspm etc., because NPM hosts pretty much all popular JS libraries.

Installing client tools and libraries

Open up cmder and change your directory to “C:\tutorial\parts\modern”. Then, install the client side tools: TypeScript and typings using the command:

npm install typescript@next -g
npm install typings -g

Since TypeScript and typings are only required at the development time and need not have to be deployed into the web server, we don’t need to pollute our library dependencies. Hence they are installed globally. For those who get the project from source control like github, it is a good idea to add them as devDependencies into npm’s package.json as well using the following commands:

npm install typescript@next --save-dev
npm install typings --save-dev

NPM command line switch “--save-dev” indicates NPM that the packages are only development time dependencies. NPM updates its own package.json file that tracks whatever you install using npm. To check the versions of TypeScript and typings installed, run these commands:

tsc -v
typings –v
fig1

Project organization for client side source code

You might be wondering where should we create our client side source code files and how would ASP.NET core differentiate between server side vs client side code. Those are very genuine concerns and let us address them. In ASP.NET core applications, there is a dedicated folder named “wwwroot” from where the client side files would be served. So, let us create that folder under our project folder. We need to write code to let ASP.NET core serve static files in order for us to server html, css and image files. Just add a call to UseStaticFiles() method in Configure() method in Startup.cs right above the UseMvc() call where we configured the routes.

app.UseStaticFiles();
          
app.UseMvc(
                routes => { routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
});
          

Writing our first TypeScript class

Now, let us focus on writing our first class in TypeScript. Create a folder named src outside of wwwroot folder. Then, create a folder named “app” inside that “src” folder. TypeScript files should be created with .ts extension. Create a new file named “greeter.ts” with the following TypeScript code under “src\app” folder:

class Greeter {
    constructor(private message: string) {
    }
    sayHello() {
        console.log(`Hello ${this.message} from TypeScript!`);
    }

    get greetingMessage() : string {
        return `Hello ${this.message} from TypeScript!`;
    }
}

 

After creating the folders and greeter.ts, your directory structure should look like this: fig2

 

Transpiling TypeScript source code and using it from HTML

There are many ways to transpile a TypeScript file into JavaScript. Here are a few options:

1. Run tsc compile from command prompt with the source files as arguments. I would prefer running the tsc command with –watch switch so we don’t have to

2. Setup a tsconfig.json with all parameters required for TypeScript compiler. Any folder that contains tsconfig.json will be considered a TypeScipt project. This is the preferred approach because using tsc without any specific source files will use the parameters in tsconfig.json.

3. Use build tools like grunt or gulp and configure their typescript tasks, which would leverage tsconfig.json.

4. Use Webpack with awesome-typescript-loader that will transpile the TypeScript files into JavaScript files

For this part of the series, I’d go with creating tsconfig.json and running the command “tsc –watch” from cmder. Some of you might be thinking why couldn’t I leverage VSCode’s tasks.json to run tsc task. Unfortunately, at the time of writing this blog post, VSCode only supports one top level build task. Although many forums and discussions in Stackoverflow suggest that we can use “bash” or “cmd” as the top level command and add sub tasks to run typescript followed by dotnet CLI tools. IMHO, it is a total waste of time because you would be better off using gulp or grun as the top level command and use subtasks to run the individual tasks/targets within gulpfile/gruntfile.

Since I’ll be showing how to configure Webpack (the module loader/build tool of my choice) to transpile TypeScript into JavaScript in later parts of this series, let us use tsc compiler from the command line with “-watch” switch enabled to watch for changes in our project folder.

Creating a tsconfig.json project file

From within VSCode, add a new file named tsconfig.json that reads like this:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "inlineSourceMap" : true,
        "inlineSources" : true,
        "sourceRoot": "src/app",
        "outDir": "wwwroot/app"
    }
}

Now, let us start the TypeScript compile with –watch option from cmder as follows:

tsc -watch

As soon as you type the command and hit enter, all .ts files in our project folder will be transpiled into .js files base on the settings inside of tsconfig.json. If you noticed, I have configured the outDir parameter to “wwwroot/app”, where the transpiled .js and .js.map (source map is used by browsers for debugging) will be generated.

fig4

fig5

Using the transpiled JavaScript files from index.html

Now, we need to start using those transpiled JavaScript files in our index.html. Add a <div> element, construct an instance of our Greeter class and use it’s greetingMessage property to set the innerHTML property of that <div>. Here’s the index.html:

<html>
<head>
    <title>Welcome to ASP.NET Core 1.0</title>
    <script src="app/greeter.js"></script>
</head>
<body>   
    <div id="greeting">
    </div>
    <script>
        var greeterObj = new Greeter("World");
        document.getElementById("greeting").innerHTML = "<h1>" + greeterObj.greetingMessage + "</h1>";       
    </script>
</body>

</html>

After making the changes in index.html, hit F5 to launch the browser, navigate to http://localhost:5000/index.html and you should see the message "Hello World from TypeScript!". Since we have enabled source map options inside tsconfig.json, we can also set breakpoints in TypeScript source files and debug in browsers.

fig3

We are now able to write our client side code using TypeScript. In the next part of the series, I’ll show how to setup Aurelia, a powerful, modern JavaScript framework and Webpack module bundler to continue building our modern web application. Happy coding!

Part 1: Building a web application using ASP.NET Core 1.0, AureliaJs, TypeScript, WebPack in Visual Studio Code – Part 1

2 comments:

  1. There are various no. of technologies that are emerging and becoming popular in the field of web development. ASP.Net is also a good platform to work on.
    ASP.net Web Application

    ReplyDelete
  2. You deserve to work with talented engineers who share your corporate culture and values — and we are here to help you find them. Hiring A Remote Software Engineer.

    ReplyDelete