SharePoint Framework (SPFx)

Share

As a SharePoint developer I have traced different approaches and possibilities of the SharePoint customizations over the years. If you are my colleague, working with SharePoint, you have probably experienced different ups and downs working on SP projects, especially in the development department as the customization approaches have changed over the years and versions of the platform. So, we have built C#/.NET based web parts exclusively in the beginning, but we have also used Script Editor Web part – it was easy to customize DOM on the classic SP sites this way, but we have learned that it cannot be used on “NoScript” sites. Later we got App Parts – Developed using Add-in model, placed in an iframe. Development of it is a little bit complicated and it is not able to access DOM of SP page.

So finally, we have a new approach and it is called SharePoint Framework or shorten SPFx that can be used for development against latest SharePoint On-Prem versions (2016, 2019) and SharePoint Online on O365. This new framework is following the evolution of the platform, so it is meant to be used for customization of modern SharePoint pages and creation of the web parts that can be used on modern and classic sites. It can be entirely developed using client-side languages and open source tooling which makes it dev platform and framework agnostic. SPFx provides an easy integration with SharePoint data.

Here are some of the key features of the SPFx:

  1. No iframes, runs within the context of the user browser and connection in the browser
  2. Faster rendering on the browser as all controls all rendered in normal DOM
  3. Controls are responsive
  4. Runs in the context of current user
  5. Gives controls to access the lifecycle of the SharePoint Framework webpart (component) (Init, render, load, serialize, deserialize, configuration changes and many more)
  6. No dependency on underlying Framework. You can use any framework like React, Angular, Knockout and more
  7. Open source Development tools are used (npm, TypeScript, Yeoman, webpack and Gulp)
  8. Can be added on both classic pages and modern pages
  9. Safe and Secure, need tenant access to deploy/make changes to the SPFx webpart
  10. Controlled visibility, we can decide who can view this webpart in the App Catalog of the site contents
  11. You can leverage your earlier knowledge of CSOM, as the data models are not changed and is completely transferable
  12. SPFx webparts can be used with classic or modern sites in SharePoint
  13. Supports mobile views of SharePoint Online sites

Tools

So, for the SPFx development things have changed pretty much regarding the toolset needed. As I have mentioned earlier, it is system and framework agnostic which means that now SharePoint development is done with open source tools, on any operating system and a lot of different JS frameworks can be used. Regarding to previous development toolset, following image is showing what is the difference:

Let’s check what do we need to start on SPFx development.

Setup Developer Environment for SPFx

  1. Install Node JS
    1. Install latest LTS version from https://nodejs.org
    2. If you already have NodeJS installed, check the version
       node -v
  2. Install Code Editor
    1. Install any of below code editors,
      1. Visual Studio Code (https://code/visualstudio.com)
      2. Atom (https://atom.io)
      3. Webstorm (https://www.jetbrains.com/webstorm)
      4. Visual Studio SPFx Project Template (https://marketplace.visualstudio.com/items?itemName=SharePointPnP.SPFxProjectTemplate)
  3. Install Yeoman and gulp
    1. npm install -g yo gulp
  4. Install Yeoman SharePoint Generator
    1. npm install -g @microsoft/generator-sharepoint
  5. Updating NPM packages
    Yo, Gulp, Yeoman SharePoint Generator gets installed as NPM packages. Use the below commands to check and update them.

    1. To update NPM
      1. npm i -g npm
    2. To check outdated packages
      1. npm outdated –global
    3. This command will report packages that need updates. Use the below command to update the reported packages.
      1. npm update -g <package-name>

Building your first SPFx project

For this topic, it should be good if you have basic to medium understanding of SharePoint, especially latest version and Online, understanding of PowerShell or any other command line tool and experience with JavaScript.

Here we will create a small Hello World Web Part for SharePoint Online on O365.

First we will create a project folder called helloworld-webpart.

 

 

 

 

 

 

 

Open PowerShell (or command line tool of your choice) and go to the project directory.

Create a new HelloWorld web part by running the Yeoman SharePoint Generator.

yo @microsoft/sharepoint

For this example, follow the answers as on image below. You can accept proposed default values by just clicking Enter button.

 

Next question will be about the JavaScript Framework which we like to use. For this example, we will select No JavaScript Framework. If you are, for instance, experienced React developer you can later try this same example with selecting React framework or you can further investigate to use other available frameworks in this context.

At this point, Yeoman installs the required dependencies and scaffolds the solution files along with the HelloWorld web part. This might take a few minutes.

You will see Congratulations Message once it is done.

Following command must be executed only once in your development environment, so you can skip this step, if you have already executed that in your environment. It will install developer certificate.

gulp trust-dev-cert

Now comes a funny part. All SP developers know how it is painful that you always need SharePoint Server installed on your dev machine to debug web parts and even to see their visual representation. Things have changed, so with SPFx we can preview our work on a local machine without having SP installed. It is, of course, simulated SP environment but doing exactly what we need.

So, while in a helloworld-webpart folder with your command line, just type:

gulp serve

This command executes a series of gulp tasks to create a local, node-based HTTPS server on localhost:4321 and launches your default browser to preview web parts from your local dev environment.

Your default browser will open the local workbench.

Here you can test adding your web part to the page.

When the Web Part is added, click on edit icon to open Web Part Property Pan:

You can now try to change the Description field. Observe the Real Time change in the web part.

Ok, lets now observe the provisioned project. Open your helloworld-webpart folder with Visual Studio Code (or Code Editor of your choice).

Web part code is located in \helloworld-webpart\src\webparts\helloWorld.

There is more important information regarding this project structure for more complex implementations and I do encourage you to investigate further, for this showcase we will focus only on web part files.

First file to observe is HelloWorldWebPart.manifest.json. It is where the manifest of the web part is located, things like type, alias, id and web part group, title, description and set of values for predefined properties.

Next file is HelloWorldWebPart.module.scss where we have all stylings used for our web part. For this case we will not change it.

Finally, we have HelloWorldWebPart.ts where our web part logic is together with its representation renders.

Let’s do some cool changes. First, let’s change this real time web part property pan behavior. So, when the property is changed, request from user to click on a button for the change to be reflected.

Add following to your HelloWorldWebPart.ts file:

protected get disableReactivePropertyChanges():boolean{
    return true;
  }

Save your changes and go back to your PowerShell and type gulp serve again. Check the behavior of your property pan in your local workbench.

As you can see, the change will be visible on the web part only after you click Apply.

Now, lets try to add more controls to our web part. Let’s say the idea is to have a dropdown with some selection of colors on the Property Pan of the Web Part. What is selected there, should be visible in the Web Part. Of course, you can imagine more complex scenarios with custom properties implementation.

First add Property Pan Dropdown control:

Replace your getPropertyPaneConfiguration method code with following:

protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel,
                }),
                PropertyPaneDropdown('color', {
                  label: 'Dropdown',
                  options:[
                    {key: 1, text: 'Red'},
                    {key: 2, text: 'Blue'},
                    {key: 3, text: 'Green'}
                  ]
                })
              ]
            }
          ]
        }
      ]
    };
  }

This will create options for the property pan dropdown control which we will use for selection.

Add the following line to your render method:

<p class="${ styles.description }">Selected color:${escape(this.properties.color)}</p>

This will be representation of our choice on the Web Part.

Now you will probably get color property underlined like on image. This is because we didn’t yet define the global color property of the web part. Do this here and observe how the property color will resolve in the render method:

Now, only thing that we can do more is to define our default value for the color selector. Do this in your HelloWorldWebPart.manifest.json file by adding line like on image:

Save all your changes and do gulp serve again from your command line.

Add your Web Part to your local workbench. Observe your new text control on a web part representing defined default value:

Click Edit option to open Properties Pan:

We can now use our Dropdown selection control and observe the change on the web part after the Apply button is clicked.

Checking the change.

Ok this was nice introduction, but let’s do a more usable case now. What if we need something from the underlaying SharePoint site? Let’s try to show all lists from the actual site, what do you think? You will probably ask now how we can show lists if our local workbench is not actually SharePoint installation. And the question is good. Now we will use O365 and SharePoint online to help us here.

Before we start, if you didn’t find it on your own, to break gulp serve command click Ctrl+C in your command line, it will ask for yes and now.

Click Y and then Enter if you agree to stop the process.

Ok, get back to work. Now again open your HelloWorldWebPart.ts for edit and add following getListInfo function to it:

private getListsInfo(){
    let html: string = '';
    if (Environment.type === EnvironmentType.Local){
      this.domElement.querySelector('#lists').innerHTML = "Sorry wont work";
    } else {
      this.context.spHttpClient.get(
        this.context.pageContext.web.absoluteUrl + '/_api/web/lists?$filter=Hidden eq false', 
SPHttpClient.configurations.v1)
        .then((response: SPHttpClientResponse) => {
          response.json().then((listsObjects: any) => {
            listsObjects.value.forEach(listObject => {
              html +=`
                    <ul> 
                      <li>
                        <span class="ms-font-1">${listObject.Title}</span>
                      </li>
                    </ul>`;
            }); 
            this.domElement.querySelector('#lists').innerHTML = html;
          });
        });
      }
    }

We will not go trough complete code of this method, but experienced readers will understand it. Anyhow, we will mention our old friend context and SP Dev colleagues will be happy that its usage is nicely supported here and you can easy fetch all objects from it.

You will see red underlined Environment, EnvironmentType and SPHttpClientResponse as these namespaces are not yet defined. To do so, add following lines to your ts file:

Also, we must use our function somewhere, so let’s call it from our render method and add a div for lists.

Save everything and try gulp serve from your PowerShell.

So here we used a nice thing called Environment selector in our code. This is manly used when developing so it will help us if we try to debug and preview on a wrong environment:

As you can see, here we are checking if web part’s current environment is local and if yes it will give us custom message, if not it will proceed and try to fetch site lists. Now the question is how to test this against real SharePoint. Here we will use our O365. I am strongly suggesting all developers and others to check O365 Developers Program which gives you O365 E3 subscription for one year and of course for development and testing purposes.

Assuming you have your O365 configured, open following location:

https://yourtenantname.sharepoint.com/_layouts/15/workbench.aspx

What you will see there is a same thing as your local workbench, but this is on actual SharePoint, so it will enable us to use context of the current page, site, web and user. Very important here is that you will now serve your web part from your development machine and preview it on your workbench on O365. I am encouraging you to investigate deeper about setting CDN and deployment strategies regarding the SPFx – this part will not be covered in this blog post.

Now, while you are serving your project from your machine with gulp serve command, go to the mentioned o365 location and add your web part:

Observe that there are now all expected web parts from regular SharePoint Modern experience WP gallery.

After the web part is added we will see all Lists from the actual site but also working Dropdown property with colors:

I hope you liked this post. My intention was to introduce SP Dev colleges into this new way of customizing SharePoint but also to show to frontend developers that now they can easy jump into our world and help us create nice Web Parts and Extensions with rising JavaScript Frameworks. As mentioned somewhere in the post, I didn’t cover all the details here but I hope this is enough for you to start playing and investigating SPFx.

 

Share

Sign in to get new blogs and news first:

Leave a Reply

Uroš Đorđević

Senior IT Consultant / Software Engineer @PRODYNA
mm

With almost 15 years of experience working with Microsoft SharePoint platform, Uroš is today on a position of Senior IT Consultant / Software Engineer in PRODYNA. Previous work is related to large scale SharePoint projects for banks, government institutions and enterprise business. Through these year Uroš gathered a professional experience and knowledge in fields of SharePoint development, administration, migrations and consultancy regarding the topic.

Sign in to get new blogs and news first.

Categories