TypeScript Tips and Tricks

Automatically compile TypeScript files when using VS Code

If you’re writing TypeScript using Visual Studio, your files are automatically compiled when you save (assuming you haven’t turned this off…the feature is found in the Project Properties > TypeScript Build screen).

If you don’t use Visual Studio, and instead are using a lightweight IDE such as VS Code or Sublime Text, you don’t get this feature.

Manual compilation

First things first, how would you normally compile a TypeScript file to JavaScript? VS Code doesn’t do this out of the box (perhaps the will add this functionality in the future, I’m not sure). You use a task runner.

To configure a task runner, open your project that has some TypeScript files, and press Ctrl+Shift+B. A little notification to appear that tells you that no task runner is configured. Click Configure Task Runner. VS Code will create a directory called .settings and add a new JSON file called tasks.json to this directory.

Open tasks.json and inspect the default configuration (the one that isn’t commented out, VS Code will show you some other sample configurations that are commented out. Look for the following line;

"args": ["HelloWorld.ts"]

Change this path to point at a TypeScript file in your project. Save changes.

Now open your TypeScript file, and open in it in side by side view. Put the TypeScript file (.ts) on the left, and put the compiled JavaScript code (.js) on the right.

Make a change your TypeScript file and press Ctrl+Shift+B again. You should see the updated JavaScript file.

Automatic compilation

Having to press Ctrl+Shift+B every time you want to compile your TypeScript files gets really old, really fast. Lets say to make a change, you refresh your browser and the change hasn’t been applied. You open the dev tools, start debugging, and hang on…where is your code? Oh right yeah, you forgot to run the task runner. Rinse and repeat.

Instead of using a task runner to call the TypeScript compiler (tsc.exe), we can instead make tsc work for us, using the -w flag, called the watch flag.

Wrong Way

My first thoughts when trying to get this to work were to pass the -w flag to tsc using VS Code. Try opening tasks.json and changing the args option as follows;

"args": ["-w", "test.ts"],

Yeah that doesn’t work (even though other sample configurations shown in the same file pass commands to tsc in this manner).

Right Way

The best way to do this is via the command line. Open a Node.js command prompt window, and change directory (cd) to your project folder. Now run the following command;

tsc -w

This will listen for changes in the given directory, and all sub directories. Whenever a change is made, the file will be recompiled automatically. So now, pressing Ctrl+S on the keyboard will cause the file to be recompiled.

We’re almost there. If you want the file to automatically compile pretty much as you type (not quite that frequently, but almost as good), you can enable Auto Save in VS Code. Click File > Auto Save to turn it on.

Success! All your TypeScript files will be automatically saved and compiled as your work on them, with no keyboard presses needed.

I mentioned Sublime text at the beginning of this tip, because of course this isn’t a VS Code specific feature. You can easily enable this regardless of the editor you are using.

Source maps

Source maps are are means of rebuilding compiled and minified code back to its original state. When you write TypeScript, it is transpiled to JavaScript and can be minified to reduce bandwidth costs and improve page load times. This process, however, makes debugging virtually impossible due to the fact that all variable names are changed, all white-space and comments are removed etc.

Browsers use source maps to translate this code back into its original state, enabling you to debug TypeScript code straight from the dev tools. Pretty neat huh?!

Modern browsers (IE10, Chrome, Firefox) enable source maps by default.

However, I have on many occasions encountered errors and inconsistencies when using source maps, and it is not just me who is encountering these issues. The dev tools might tell me, for example, the wrong value for this. TypeScript captures the value of this in a local variable, so that, in theory, you’re always using the right this (it typically captures the instance of the class itself). Often, however, dev tools will incorrectly tell me that this is an instance of window… rendering the debugger useless.

How to turn source maps off

There are a couple of ways to approach this.

Stop generating source maps

TypeScript is generating the source maps for you.

If you are using Visual Studio, you can stop generating source maps by going to Project Properties > TypeScript Build and un-checking Generate Source Maps. Be sure to rebuild your project.

For everybody else, you simply don’t pass in the –sourcemap argument to tsc.

Disable source maps in the browser

Modern browsers have the ability to disable source maps.

Chrome
1. Open dev tools
2. Settings
3. Sources (middle column)
4. Enable JavaScript source maps

Firefox
1. Open dev tools
2. Debugger
3. Settings
4. Un-tick “Show Original Sources”

Combine output in a single file

There are a bunch of tools available to take care of bundling and minification of JavaScript files. You’ve probably used either ASP .NET Bundling & Minification, Web Essentials bundler, Uglify or something similar. These tools generally work well and I’ve only experienced minor problems with each tool. (The ASP .NET bundler is a bit more troublesome than most, to be fair).

When using a task runner such as Grunt or Gulp, you pass in an array of all the file paths you want to include in the bundle.

Example;

files: {
        'dest/output.min.js': ['src/input.js']
      }

Generally I don’t take this approach of passing in individual files, I prefer to pass in a recursive path, perhaps something like this;

"**/*.ts"

That aside, if you prefer to include your files individually in Grunt/GulpFile, TypeScript can help you out by combining all the compiled JavaScript into a single file.

Using Visual Studio

If you’re using Visual Studio, there is a simple user interface to set this up. Right click your project and select Project Properties > TypeScript Build.

Under the Output header, there are two options of interest;

  1. Combine JavaScript output into file: – Name of the file to put the merged JavaScript.
  2. Redirect JavaScript output to directory: – The folder in which to put the merged file.

Typically you would use these two in conjunction with each other. You can then modify your Grunt/GulpFile to point at the merged file, rather than all your un-merged JavaScript files.

Via command prompt

The flags you need are as follows;

--out FILENAME
--outDir DIRECTORYPATH

Available from version 1.5

Version 1.5 of the TypeScript compiler (version 1.5.3 to be precise, use the -v flag to check you aren’t using 1.5.0 beta) adds a few additional features of some use (this is not an exhaustive list);

-m KIND or –module KIND

Ok this isn’t new, but TypeScript 1.5 has added support for UMD and System, so you can now pass the name through to use that module system. There is an updated UI in Visual Studio 2015 RTM for this feature.

–noEmitOnError

Doesn’t generate any JS files if any compile time errors are detected. You might want to turn this off if you want to ignore certain errors (like, incorrect or incomplete type declaration file).

–preserveConstEnums

The default behaviour in past versions of tsc was to remove enumerations and replace them with te actual value of the enumeration.

So if your enum was;

enum DaysOfWeek{
    Monday,
    Tuesday
    ... 
}

...

console.log(DayOfWeek.Monday)

The transpiled output would be;

console.log(0 /*Monday*/)

Passing the –preserveConstEnums flag prevents this transformation from taking place, so the original code stays in act.

Summary

The TypeScript compiler is flexible and configurable and has a wealth of flags that can be passed to it to change the transpiled output. Using Node.js tools, you can easily have your TS files automatically transpiled, you can have source maps for a better debugging experience, and you can have all the transpiled TS files merged into a single file for easier uglification.

I’ll update this post with new tips and tricks as I come across them. If you ave any good ones, let me know in the comments or get me on Twitter, and I’ll update the post accordingly.

If you’re interested in learning about all the different compiler flags that TypeScript accepts, you can find them in GitHub.

ASP .NET 5 (vNext), first thoughts

Microsoft ASP .NET 5 is a major shift from traditional ASP .NET methodologies. Whilst I am not actively developing ASP .NET 5 applications at the minute, .NET has always been my bread and butter technology. When I look at industry trends here in the UK, all I see is .NET .NET .NET, therefore it is important to have one eye on the future. I’ve watched all the introduction videos on the ASP .NET website, but I also wanted to take a look at what ASP .NET 5 means to me.

This is not meant to be a fully formed post. This will come later down the line. Right now, I think ASP .NET 5 is evolving too quickly to be “bloggable” fully.

Version disambiguation and terminology

Lets take a second to disambiguate some terminology. Microsoft’s understanding of versioning has always been different to everybody else. This tweet from Todd Motto really sums it up;

Looks like versioning is not going to get any simpler for the time being

ASP .NET 5 (ASP .NET 4.6 is the current version)

Previously known as ASP .NET vNext, ASP .NET 5 is the successor of ASP .NET 4.6. In the past, versions of ASP .NET have followed the .NET Framework release cycle. It looks like that is coming to an end now. ASP .NET should not be confused with MVC. ASP .NET is a technology, MVC is a framework.

ASP .NET 5 is currently scheduled for release in the first quarter of 2016, as per this tweet from Scott Hansleman; (I suspect this date will slip though)

The ASP .NET team would rather “get it right” and take longer, than rush the product and get it wrong (which would spell long term disaster for the platform)

MVC 6

This is the new version of Microsoft’s Model-View-Controller framework. There is a nice post on StackOverflow that describes the new features of MVC 6. Here are a few of the best;

  • “Cloud optimization” … so better performance.
  • MVC, WebAPI and Web Pages are now unified.
  • Removed dependency on System.Web, which results in more an 10x reduction in request overhead.
  • Built in dependency injection, which is pluggable, so it can be switched out for other DI providers.
  • Roslyn enables dynamic compilation. Save your file, refresh the browser. Works for C# too. No compilation required.
  • Cross platform.

DNX (.NET Execution Environment)

The .NET Execution Environment, DNX, is a cross platform thing that will run your .NET applications. DNX is built around the .NET Core, which is a super lightweight framework for .NET applications, resulting in drastically improved performance thanks to a reduce pipeline. Dependency on the dinosaur assembly System.Web has gone, but in return you are restricted to more of a subset of features. This is a good thing, my friend. System.Web has every featured imagined over the last 13 years, 75% of which you probably don’t even care about.

Interesting new features and changes

  • Use of data annotations for things that would previously have been HTML helpers (Tag helpers)
  • Environment tag on _Layout. Enables a simple means to specify which resources to load depending on the application configuration (Debug mode, release mode etc)
  • Bower support
  • Gulp out of the box (interesting that they chose Gulp over Grunt, I think its Gulps superior speed that has won the day.)
  • .NET Core. Drastically reduced web pipeline, could result in 10x faster response in some cases (remains to be seen!).
  • Noticeably faster starting up.
  • Save to build. With Roslyn, it is now not necessary to build every time you make a change to a CSharp (.cs) code file. Just save and refresh. Compilation is done in memory.
  • Intellisense hints that assembly is not available in .NET Core (nice!)
  • Built in dependency injection, which can be switched out for a third party mechanism.
  • Web API is now no longer a separate component. Web API was originally a separate technology from MVC. The two were always very alike, and it makes sense that the two should be merged together.

Deleted stuff

  • Web.config has finally been removed and exchanged for a simpler JSON formatted file. Parties have been thrown for less.
  • packages.config has gone, seems redundant now that things are in line with how the rest of the web develop, i.e. using package.json

Bad points

  • Still heavy use of the Viewbag in default projects. I’d like to see the ViewBag removed entirely, but I suspect that will never happen.
  • The default project template is still full of “junk”, although it is now a bit simpler to tidy up. Visual Studio automatically managers bower and npm packages, so removing a package is as simple as deleting it from the package.json file.

Summary

I am very keen to get cracking with ASP .NET 5 (vNext), although at the time of writing I feel that it still a little bit too dynamic to start diving in to at a deep level. The introduction of .NET Core, a cross platform, open source subset of the .NET framework is awesome… I can’t wait to see the benefits of using this in the wild (reduced server costs!!! especially when running on a Linux based machine, although it remains to be seen). The ViewBag still exists, but we can’t have it all I suppose.

At this point, we’re at least 5-6 months away from a release, so develop with it at your own risk!

Using Gulp-SASS with VS Code task runner

With the task runner built in to VS Code, you can set up Gulp to automatically compile your SASS files to CSS with a simple key press.

VS Code task runner prerequisites

To be able to get this working, you need the following prerequisites

To install Gulp run the following command;

npm install -g gulp

or

npm install gulp --save-dev

To install into your development environment. I’d generally recommend installing gulp globally as you will likely be using it a lot.

You will probably want to install gulp-sass locally in your dev environment. We will get to that shortly.

Existing Project

If you are using an existing project and you already have a Gulp file (GulpFile.js) and a package.json file, feel free to skip the next step.

New Project

Create a new folder for your project, open VS Code and click File > Open Folder. Point to your new folder and click OK.

Open a Node.JS command prompt, and change directory to your new folder.

Now type the following command;

npm init

As shown here;

npm init

You will be prompted to enter details about your project. Either accept the default by pressing Enter or enter the details as appropriate. This will generate a package.json file for your project.

Configure the task runner

The quickest, easiest way to configure the task runner is to press Ctrl+Shift+B and click the Configure Task Runner button.

Configure Task Runner

VS Code will switch to a file called tasks.json. This file contains several possible configurations depending on what you want to do.

Ensure that all configurations are commented out, then all the following configuration;

{
    "version": "0.1.0",
    "command": "gulp",
    "isShellCommand": true,
    "tasks": [
        {
            "taskName": "sass",
            "isBuildCommand": true,
            "showOutput": "silent"
        }
    ]
}

This will execute gulp, and will run the sass task (which we haven’t defined yet).

GulpFile.js

Either open or create a new file called GulpFile.js, at the root of your project.

If you just created a new GulpFile, add the following JavaScript;

'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function () {
  gulp.src('*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./'));
});

gulp.task('sass:watch', function () {
  gulp.watch('*.scss', ['sass']);
});

or if you are editing an existing configuration, note that you don’t need to re-import Gulp.

Note: For simplicity, this configuration assumes that your SASS files are in the root of your project. In most cases, this will not be true.

If, for example, your SCSS files are contained in a folder called Content, you might use the following path instead;

./Content/**/*.scss

The same applies to the destination folder, as defined by;

gulp.dest('./')

Ensure this path is appropriate to your project structure.

npm install

To install Gulp into your development environment, go back to package.json and add the devDependencies section as shown below;

"devDependencies": {
    "gulp": "~3.9.0",
    "gulp-sass": "~2.0.4"
  }

Your final package.json file may look something like this;

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "gulpfile.js",
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "gulp": "~3.9.0",
    "gulp-sass": "~2.0.4"
  }
}

Go back to the Node.JS command prompt and type the following command;

npm install

This will create a new folder in your project called node_modules, which will in turn contain each dependency.

Compiling the SCSS files

Add a new SCSS file to your project and add some dummy CSS;

body { }

Now with everything set up, press the Ctrl+Shift+B keyboard combination to kick off the task.

Task Finished

If all goes well, the corresponding CSS files should be compiled for you.

Summary

VS Code has a very powerful and versatile task runner built in that can be configured to run just about any task. We have created a GulpFile, and told VS Code how to run Gulp and which tasks to execute, using the tasks.json configuration file. In this case we have configured the Gulp-SASS npm package, but there are no limitations on what packages you can use. You can also add multiple tasks that do just about anything.

Finally…

If you encounter any problems, let me know via the comments section below, or via Twitter and I’ll be more than happy to help you out.

Why Visual Studio 2015 has changed my life

I’ve been using Visual Studio on an almost daily basis since 2002. Before that, my development tool of choice was Visual Basic 6 (Visual Studio 6). The shift between those two versions felt like using a whole new product at the time. Since then, changes to Visual Studio have been incremental. Microsoft have released a new version every 2-3 years. Visual Studio 2015, however, feels like another significant paradigm shift.

The point of this post is not to outline all the shiny new features, there are official blog posts for that. No. I wanted to tell you how the changes to Visual Studio have directly changed the way I work on a day to day basis.

Visual Studio Tasks (Task Runner Explorer)

The wider web development community has been using task runners, GruntJS and more recently GulpJS, for at least the last few years.

On every project I work on these days, I use TypeScript and SASS. Web essentials previously was responsible for compiling my SASS files, as well as providing linting for both SASS and TypeScript. With the 2015 release, this functionality has been removed. There are a bunch of Mads Kristensen extensions on Visual Studio Gallery that you can install that will add this functionality back in.

However, why not cut out the middle man and set up these tasks yourself?

With tasks you can;
* Automatic SASS/SCSS compilation using Ruby gem (and a watcher that “listens” for changes to files as you make them)
* SCSS and TypeScript Linting, with your own linting configuration files directly in the project (perfect for sharing with team members)
* Better bundling and minification. You can use something like UglifyJS instead of the old ASP .NET bundler (which was horribly buggy!)
* But most importantly, the door is open to a world of possibility.

Tasks enable you to automate tedious repetitive tasks and share those efficiencies easily with your team, whilst not restricting you to a particular subset of tools.

Reduced dependence on ReSharper

I’ve been a fan of ReSharper for a long time and I’ve even blogged about why I can’t work without it. All this said, however, its truth time. I don’t want to have to depend on a third party tool to make my IDE more useful. I want Visual Studio to be awesome enough on its own that I don’t have to install any third party tools to make it usable.

ReSharper introduced the lightbulb menu several major versions ago. The lightbulb menu introduces many code refactorings, such as implement interface, refactor this, and so many I can hardly think. The newly introduced native lightbulb menu in Visual Studio 2015 adds some nice refactorings.

Unfortunately, Visual Studio 2015 doesn’t go quite far enough in this respect, hence why the section is named Reduced dependence on ReSharper. I do expect this feature to get a lot of attention during this release, assuming that the open source community can tap into it easily enough.

Lambda Expressions

Lambda expressions and LINQ were introduced in version 3.0 of the .NET Framework, roughly 8 years ago. Debugging support for lambda expressions was non existent in the first versions, and was incrementally improved over time.

To start off with, you couldn’t debug any method that contained a lambda expression. Not only that, but if any method in the call stack contained a lambda expression, even if your method did not contain a lambda expression, you couldn’t use edit and continue.

Then a subsequent release solved this problem, you could still not edit and continue a method that contained a lambda expression, but the call stack problem was gone.

Now with Visual Studio 2015, you get the full debugging experience. You can edit methods that contain lambda expressions, and you can edit lambda expressions directly, and edit & continue in the same way you could with any other code before. This is a major time-saver.

You’ve never been able to add watches or use the immediate window to debug lambda expressions. With Visual Studio 2015, this is no longer the case. Rejoice.

Summary

Visual Studio has introduced the task runner explorer, which can run tasks on various IDE events (Open, before/after build etc.). This really opens the door to “the rest of the web development world”, where sophisticated tooling exists to automate mundane tasks such as bundling, linting, pre/post processing and so much more. Developers are no longer tied to doing things the Visual Studio way. Other enhancements such as the lightbulb menu and better debugging will save developers time and reduce dependence on third party tooling.

Why I don’t want to be a front-end web developer

The job title isn’t representative of my skill set

As a front-end developer, you portray yourself as having a narrow set of skills. This probably isn’t the case.

I did a quick search on a popular job forum for front-end developer jobs, and there is a clear recurring theme as to what skills are required to be a mid-level/senior front-end developer;

  • (X)HTML (5), CSS, SASS/SCSS, LESS.
  • Backbone, Angular, Knockout.
  • Responsive web design (I’m assuming Bootstrap knowledge, Foundation etc).
  • Adobe Photoshop, Magento.
  • Knowledge of source control and some form of client side unit testing.

My perception of these skills;

  • HTML has remained relatively unchanged since it was invented in 1990. If you don’t agree, just take a look at the source code for the first web page. HTML is easy, whatever the flavour. That’s actually is greatest strength, no barrier to entry for new developers.
  • CSS is easy to learn, impossible to be great at. Thankfully tools such as SASS/SCSS and LESS are eliminating the pain. A web developer of any skill level and experience can learn to use these CSS pre-processors in 60 minutes or less. They’re simple. They just work.
  • If you’re good at responsive web design, this is a valuable skill. Thankfully, if, like me, you’re not strong with design… front-end frameworks, such as Bootstrap and Foundation, help most developers sweep this skill gap under the rug.
  • Photoshop is in a world of its own. Its ridiculous level of complexity is only matched by its mind boggling feature set. Kudos if you can even get it to install and run.
  • Source control. All you need to know; git push and git pull.

These are, of course, tongue-in-cheek observations. What I’m trying to say is that a full-stack developer can be strong in all of these areas with minimal exposure and experience. These are not specialist skills. This generalisation I think applies to JavaScript development too. After 3 months of constant exposure to AngularJS, for example, you should have a good (if high level) understanding of how it works, how to use it, when to use it, and most importantly, when not to use it.

I don’t want to be a front-end developer because I have broader range of skills and I don’t want to undersell myself.

From a consultants perspective

Portraying yourself as a front-end developer might make sense in the short term. Developers in general at the minute are in high demand. In the UK especially there is a clear skills shortage, so presenting the image of being an expert or specialist in this field might help you land a lucrative role.

Rather than pitching as a front-end developer, however, I see more value in pitching yourself as a front-end developer with extenstive full-stack experience. That way you’re still ticking the boxes on the potential employers checklist, whilst making clear that your skill set goes much deeper.

Front end development is moving too fast

Sorry but it is. It feels like every day there is some new shiney JavaScript framework or “must have” tool that I “must have” (although if I really “must have” it is often debatable). The web is becoming more and more mature as a platform and I see this trend continuing, but we’re still some way away from being there. Yesterday all the cool kids were using PHP, then ASP .NET MVC, then AngularJS/KnockoutJS/WhateverJS. Tomorrow, ReactJS will (probably) be the framework of choice (or perhaps Aurelia will emerge as a viable competitor).

There is also and endless list of web development tools; Visual Studio, Code, Sublime, Webstorm, Dreamweaver (joking, who uses that?!), Eclipse, Netbeans, arguably Notepad++, VIM, EMACS … and infinitely more.

The net result is that I’ve spent literally hundreds of man hours learning FrameworkX (and probably a decent amount of money too) just for it to be superseeded or even die a painful death literally overnight. (Silverlight…remember that?, AngularJS 1.x according to many). It often feels like despite my best efforts, and regardless of how many hours of effort I put into my own education, my skill level is actually declining.

The pace needs to slow down and things need to stabilise before I can even consider specialising as a front-end developer.

I don’t want to be a front-end developer because I can’t (and don’t want to) half kill myself trying to keep up with the trend setters.

Front-end developers are probably not designers

I’ve found through experience that generally technical people fall in to one of two categories. I agree that this is not true in all cases.

  1. You are either a logical thinker aand prefer to write code
  2. You understand how to make things look beautiful.

Typically you don’t get too many coders with excellent design skills and vice versa.

Speaking personally, I’m a strong coder and always have been. I can scrape by when it comes to design, usually be utilising frameworks such as Bootstrap or Foundation, but I don’t excel at this.

There is a perception that front-end developers are good coders and good at design (take a look at the aforementioned job advertisement skill list, specifically the mention about Adobe Photoshop knowledge). Employers are hiring front-end guys and expecting them to be good at writing code and designing pretty websites. I think this is a mistake and the roles should be seperate.

I don’t want to be a front-end developer because I’m not a strong enough designer, and don’t claim to be. Employers have unrealistic expectations about what they will get from a front-end developer.

Front-end developers earn less money

Its true.

Developer vs Front-end Developer

£10k difference. That’s quite a gap. And that’s just one example.

I don’t want to be a front-end web developer because I want to reach my full earnings potential.

Summary

I don’t want to be a front-end developer because I don’t want to undersell myself, because I want to reach my full earnings potential, and because I don’t want to half kill myself trying to keep up with industry trend setters.

Agree or disagree… leave a comment.