Friday 27 January 2012

Working with CoffeeScript on SharePoint : Setup and Basics

So this new language called CoffeeScript was released recently and the only thing I could read everywhere was how its just JavaScript but only cleaner and more developer friendly. After digging a bit into it, I discovered that indeed the syntax is more friendlier and could boost productivity among JavaScript developers.

Also, being a SharePointer, whenever any new technology comes along, I always think about how it can be used in conjunction with SharePoint. How the technology can be leveraged to make SharePoint a better environment for developers as well as end-users.

So my natural instinct was to go ahead and see how CoffeeScript can be introduced in a SharePoint environment and how it can make life easier for the many SP developers out there. Lets get started then:

Project Setup:
For writing CoffeeScript, I have used the Mindscape Web WorkBench which is a very useful Visual Studio Extension. It lets you write code in CoffeeScript and then automatically produces a JavaScript file which contains the compiled code. This way you get to see your CoffeeScript code as well as the corresponding JavaScript code.

My SharePoint solution for working with CoffeeScript is very simple. I have created a Sandbox solution which contains a script module. Inside the script module, I deploy the MyScript.coffee, MyScript.js and the jQuery 1.7.1 files. I have included the script files on my pages with help of Custom Actions:
<CustomAction Location="ScriptLink" ScriptSrc="~Site/Scripts/jquery-1.7.1.min.js" Sequence="5000"/>
<CustomAction Location="ScriptLink" ScriptSrc="~Site/Scripts/MyScript.coffee" Sequence="5010" />
<CustomAction Location="ScriptLink" ScriptSrc="~Site/Scripts/MyScript.js" Sequence="5020" />

And lastly, I have included all the above elements in a Web Scoped Feature. Here is how my Solution Explorer Looks:
                                  (The GitHub link to my project is at the end of this blog post)

Now lets dive into the actual CoffeeScript code and see what exactly is up. Here are some interesting features of CoffeeScript that I felt are really nifty:

Here, I check the relative url of the current web and the use CoffeeScript's if else statement to modify it if necessary.
Optional parameters can be included in functions. Also, with the #{ } wildcard, parameters can be directly accessed from within a string.
Next: Working with CoffeeScript on SharePoint : ECMAScript Client Object Model
GitHub link to the project: https://github.com/vman/SPCoffeeScript

No comments: