Contents

Using TypeScript to load modules in a Visual Studio Team Services Extension

Contents

Whilst using TypeScript to work on my Visual Studio Team Services extension, I am bringing in modules using import/require:

import Service = require("VSS/Service"); 

Which compiles to the below JavaScript:

define(["require", "exports", "VSS/Service"], 

function (require, exports, Service){ ... } 

But when I run the extension I get the below error in the browser’s console:

Uncaught ReferenceError: define is not defined

/media/2016/03/define-is-not-defined.png

Visual Studio Team Services uses Asyncronous Module Definition (AMD) to load modules and when creating you need to define what modules need to be loaded. Looking through the examples provided

I found where AMD loading is set for Hub contributions, so I followed the examples and added the following to my VSS.init in the html file:

VSS.init({ moduleLoaderConfig: { paths: { "scripts": "scripts" } } }); 

// Wait for the SDK to be initialized, then require the script 
VSS.ready(function () { require(["./scripts/actions"], function (actions) { }); });

The first part explicitly states to load modules from a scripts folder, and the second part tells to load the actions.js file when the extension is first loaded. I no longer received “define is not defined” errors (hooray), but they were replaced a new error of “No handler found on any channel for message” and no loading of the menu item in the menu. I do however get the menu loading the next time I click on the menu. The above example works well for Hub contributions and not Contexts (menu items), where with Contexts my script was being loaded too late. What I needed to add was the following lines to my HTML file:

VSS.init({ explicitNotifyLoaded: true, moduleLoaderConfig: { paths: { "scripts": "scripts" } } }); 
// Wait for the SDK to be initialized, then require the script, then signal load complete 
VSS.ready(function () { require(["./scripts/actions"], function (actions) { VSS.notifyLoadSucceeded(); }); }); 

This explicitly tells Visual Studio Team Services that my extension is ready after I have loaded my scripts. My menu now loads successfully, the first time round.

Thanks to Nick Kirchem and Serkan Inci at Microsoft for helping me troubleshoot my issue.