One of the good things about the holiday season is that I’ve got plenty of free time to catch up with new developments. I suppose one of the drawbacks of being a SharePoint Developer is that I tend to focus on all things SharePoint while ignoring potentially useful developments elsewhere. One such development is TypeScript. I stumbled upon this video on channel 9 and it really got me thinking about how useful the tool is for SharePoint development, especially in light of the changes in SharePoint 2013.
In this post I’m going to look at how TypeScript can be used for SharePoint development. There are a few posts that tackle how TypeScript can be used for App development but I’m interested in building a farm solution that uses TypeScript to improve the quality of scripts that are used by my web parts.
The TypeScript compiler can be installed using the TypeScript for Visual Studio 2012 add-in. You can download it from here:http://www.microsoft.com/en-us/download/details.aspx?id=34790. For this article I’m using v 0.8.1.1.
Steps to enable this are:
- Unload the project
- Edit the project file.
- At the end of the .proj file add the following xml:
<PropertyGroup> <TypeScriptSourceMap> --sourcemap</TypeScriptSourceMap> </PropertyGroup> <Target Name="BeforeBuild"> <Message Text="Compiling TypeScript files" /> <Message Text="Executing tsc$(TypeScriptSourceMap) @(TypeScriptCompile ->'"%(fullpath)"', ' ')" /> <Exec Command="tsc$(TypeScriptSourceMap) @(TypeScriptCompile ->'"%(fullpath)"', ' ')" /> </Target>
Save the changes and reload the project and we’re good to go.
Deploying TypeScript output to SharePoint
When I’m working on a SharePoint solution I like to keep any scripts that will be deployed to the Layouts folder in a single element rather than having them scattered around in web part elements etc. To show how TypeScript can be deployed I’ll demonstrate this approach although the process is pretty much the same if your scripts are contained in other elements.
1. Create an Empty Element – rename it to Scripts
2. Delete the Elements.xml file – we don’t need it when deploying to the file system
3. Add a new TypeScript file (You can find the TypeScript template by typing Ctrl-E then typing ‘TypeScript’ and hitting enter). I’ve called my file chaholl.sample.ts
4. Once the new file has been added to the Scripts element we need to change the deployment settings for the compiled script file. Expand the chaholl.sample.ts node and select the chaholl.sample.js item.
5. Using the Properties pane set the Deployment Type to TemplateFile and expend the Deployment Location section to allow you to change the Path property to layouts\chaholl\Scripts\
If we now examine the chaholl,sample.js file we can see that the last line reads:
We can now rebuild and deploy the package and our TypeScript generated files will be deployed and ready for debugging.