HomeDeveloppementConvert javascript development to SPFX webpart for modern UI

Convert javascript development to SPFX webpart for modern UI

Edit: 03/11/2017, added steps 6.

The modern UI in office 365 requires sharepoint framework to customize some area.

In this tutorial I will explain how I have proceed to migrate a javascript mega menu to Spfx extension (the way for modern ui to add header, footer, or javascript as if it was your master page)

How to migrate ?

There is no direct migration tool. I have found recommendation from waldek blog to import the javascript using require.

This works well when the javascript acts on UI with or without jquery for example. It is not suitable if you called rest api, used $ajax method in jquery, or used javascript module for example.

Below is the method, it will take some time to adapt the js to typescript but faster than starting from scratch πŸ™‚

Change your JS file for spfx extension or webpart

This is an non exhaustive list of actions to do on your .js files.

For this scenario I needed to create a mega menu using SPFX Extension (in the top ribbon)

1. Copy JS File to spfx solution

2. Rename .js to .ts file

3. If you need to call this js in your main ts file, create a typescript class to encapsulate your JavaScript

Export class GlobalNav {




    Private function getTerms():void(){



4.From your main ts file, import the class

import { GlobalNavigation } from './GlobalNavigation';

                Let globNav:GlobalNavigation = new GlobalNavigation;

              Var terms = globalNavigation.getTerms();

5. For $ajax call, use this trick if you want to set some class attributes

Let globalThis = this;

In Ajax…sucess

globalThis.prop1 = "hehe";

globalThis.prop2 = "hehe2";

6a. Replace _spPageContextInfo.siteServerRelativeUrl  by this.context.pageContext.web.absoluteUrl

6b. Replace CSOM calls

        Function.createDelegate(this, this.onQuerySucceeded), 
        Function.createDelegate(this, this.onQueryFailed)

by arrow functions

() => {//success },
() => { //error })

6c. For $ajax, asynch false doesnt work, use promise instead

a. return new Promise<{}>((resolve, reject) => {


     Other code


7. To reference sp.js etc jsom api

a. Reference taxonomy.js etc using an helper

b. Follow this tutorial configuring config.json etc

8. Every CSOM are asynchronous, to make it synchronous, create a promise inside.


That is it for now, Ill add more when I am done migrating it, feel free to share your code migration to spfx πŸ™‚

- Advertisement -



Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.



Recent Comments