Skip to content

Creating SharePoint solutions with typescript.

October 6, 2013

This article explains how you could use TypeScript with SharePoint.

I have to confess – I hate JavaScript. I have been through Assembly language, Pascal, Java ,C , C++, C# and many other exotic things including Fortran and TeX. Could be I am getting older and more conservative, but I cannot stand the language that can change a variable type on the fly, that has no type-checking.

Unfortunately for me  – SharePoint becomes more and more JavaScripty.

To make things worse, some things I was already rather good at, are now changed. Let us take a simple example – override the way how your list looks like. I have already got used to vwstyles.xsl and even got familiar with many override techniques. Did you know, for example, that you can use the language id in XSL and make rendering the same list different for different languages?

Now the mainstream is CSR rendering and  – SharePoint moves to JavaScript. This is basically the way to operate with the site when you have SharePoint Hosted app. There is a whole bunch of new stuff. And as a SharePoint specialist I have to move into that.

Luckily there is a modern trend that helps strongly-typed guys like me to accept JavaScript.

The thing is TypeScript. TypeScript is a new rock stuff from Anders Hejlsberg and is worth many other articles itself. To be short – TypeScript gives a lot of things like strong types , classes and interfaces into JavaScript. Classes – yes, real classes, not a function within a function within a function. And you have a great intelligence.

Typescript support can be easily installed into your Visual Studio 2012+ from the official site http://www.typescriptlang.org/.

TypeScript file is actually producing JavaScript file. That is why you do not worry about browser support. You may think of TypeScript as C# that produces MSIL (JavaScript). Or think as C producing assembly code. The same code, runs on same thins, but more clear.

TypeScript definitions are generally shorter and more clear, and you have a compile time type checking. This is really important and we should not underestimate that.  Once it saved me half a day debugging when I messed up with using Moment and Date at the same time.

Once have decided using TypeScript, there is one little problem. The problem is that if you have a JavaScript file calling a library with function foo() and you want to call it, you will get a compiler error unless you have a TypeScript definition for foo. All major frameworks have this support though. To get this support, you could open a nuget package manager and type there a magic keyword “DefinitelyTyped”or just typescript and you’ll get this for almost any library you going to use.

clip_image001

A few Russian MVP’s created a great project called SPTypeScript (http://sptypescript.codeplex.com/).

This project has two major features

  1. TypeScript definitions for a big part of SharePoint CSOM.
  2. A lot of useful sampled. To name a few – custom rendering of list view + overriding forms and making new/edit forms with tabs containing native editors inside. Some samples  is an input from spdevlab.com guy Anton Vishnyakov.

Let us try to use the code from the first sample and create our own app with a list with custom rendering.

Step 1- create a SharePoint Hosted App.

clip_image002

clip_image003

Now let us create a task list instance

clip_image004

This will be a task list that we want to have custom rendering.  We want to have tasks colored based by their percentage.

But before that let us make our project support TypeScript. Out project is not a TypeScript project, thus some additional work may be required.

Press unload project and then edit project

clip_image005   clip_image006[6]

Now add the following lines to the end of your project.

  <PropertyGroup>

    <TypeScriptTarget>ES3</TypeScriptTarget>

    <TypeScriptIncludeComments>true</TypeScriptIncludeComments>

    <TypeScriptSourceMap>true</TypeScriptSourceMap>

    <TypeScriptModuleKind>CommonJS</TypeScriptModuleKind>

  </PropertyGroup>

  <Import Project=”$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets” />

Here http://typescript.codeplex.com/wikipage?title=Compile-on-Save

You can find a more specific information about these lines.

I would like to point out that you can choose ES3 or ES5 depending of which version of EcmaScript

You plan to support. ES5 is not compatible with IE8, but has cool things like properties.

Press reload project

clip_image007

Press Project\ Manage nuget packaged and find the package called sharepoint.typescript.DefinitelyTyped

clip_image008

Alternately you could run this command in the Nuget console

InstallPackage sharepoint.TypeScript.DefinitelyTyped

Now press project – right click – add new item, select TypeScript and let us create a file Mytasks.ts

clip_image009

Check that build action is set up to TypeScriptCompile.

The trick here is that for some reason the files generated by TypeScript are not added automatically to the project, so build the project, select Show Al lFiles and add the relative files into the project.

clip_image010

Now we need to make sure that our JavaScript file is connected to the list, i.e it is added to all list-relative pages.

Open your elements.xml file related to your list and add the line

clip_image011

   1: <CustomAction Location="ScriptLink" ScriptSrc="~site/Scripts/mytasks.js" />

Now let us create the code.  This is a slightly modified version of a sample you could find if you would download the Sptypescript project.

   1: module MyTasks {

   2:     export function init() {

   3:         var options: SPClientTemplates.TemplateOverridesOptions;

   4:         options = { Templates: {} };

   5:         options.OnPostRender = OnPostRender;

   6:         SPClientTemplates.TemplateManager.RegisterTemplateOverrides(options);

   7:

   8:         function OnPostRender(ctx: SPClientTemplates.RenderContext_InView) {

   9:             for (var i = 0; i < ctx.ListData.Row.length; i++) {

  10:                 var listItem = ctx.ListData.Row[i];

  11:                 var percentComplete = parseFloat(listItem['PercentComplete.']);

  12:                 var row = document.getElementById(GenerateIIDForListItem(ctx, listItem));

  13:                 if (row) {

  14:                     if (percentComplete > 0.8) {

  15:                         row.style.backgroundColor = '#f8502a';

  16:                     }

  17:                     else if (percentComplete > 0.4) {

  18:                         row.style.backgroundColor = '#52f82a';

  19:                     }

  20:                 }

  21:             }

  22:         }

  23:     }

  24: }

  25:

  26: if (document.location.href.indexOf('/Lists/MyTasks') > 0) {

  27:     SP.SOD.executeOrDelayUntilScriptLoaded(function () {

  28:         MyTasks.init();

  29:         SP.SOD.executeOrDelayUntilScriptLoaded(function () {

  30:             //Enable script with MDS

  31:             RegisterModuleInit(SPClientTemplates.Utility.ReplaceUrlTokens("~site/Scripts/MyTasks.js"), MyTasks.init);

  32:         }, "sp.js");

  33:     }, "clienttemplates.js");

  34: }

Let us discuss this part

   1: if (document.location.href.indexOf('/Lists/MyTasks') > 0) {

   2:     SP.SOD.executeOrDelayUntilScriptLoaded(function () {

   3:         MyTasks.init();

   4:         SP.SOD.executeOrDelayUntilScriptLoaded(function () {

   5:             //Enable script with MDS

   6:             RegisterModuleInit(SPClientTemplates.Utility.ReplaceUrlTokens("~site/Scripts/MyTasks.js"), MyTasks.init);

   7:         }, "sp.js");

   8:     }, "clienttemplates.js");

   9: }

SP.SOD is a classical way to lead with SharePoint ScriptOnDemand engine. We want to be sure that our code runs after the scripts we depend on are loaded.

RegisterModuleInit is explained in detail here

http://blogs.technet.com/b/sharepointdevelopersupport/archive/2013/02/08/register-csr-override-on-mds-enabled-sharepoint-2013-site.aspx

Now let us go to the init function.

Basically for this example the code is similar to what you might have had with using JavaScript. A good Intro co a client side rendering can be found here

http://www.rbradbrook.co.uk/Blog/Post/10/Introduction-to-Client-Side-Rendering-in-SharePoint-2013

In this function we do register an OnPostRender callback function. Note that we have a full access to the items themselves and also to the UI elements that has to do with these items.

Here is the result

clip_image012

To conclude the article – let us think again – why do we use typescript?

An easy answer would be : compile time checks.

Just to illustrate this – I will make  a misprint.

clip_image013

As you can see a project is not compiling.

So I hope that I could show that actually it is not a hard task to add TypeScript to your SharePoint projects. By making a few things, you will get  a huge speed up in your SharePoint projects.

Advertisements

From → Sharepoint

4 Comments
  1. alexey permalink

    typo: spdevlab.com

  2. XMarq permalink

    Hi! thank you for your post
    I’ve followed your sample step by step by but when i run the app, it doesn’t work. I’m not getting any error message, and the tasks list is even shown but without the colors.
    Any ideas of what’s happening and how can I fix it?

    Thank you!

  3. thank you!

Trackbacks & Pingbacks

  1. SHAREPOINT / JAVASCRIPT RESOURCES | Pankaj Salunkhe SharePoint Knowledge

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: