Introduction

SharePoint Framework is the new development model in which lots of work had been going on in the past year. It went to General Availability on Feb 23rd 2017. It is a page and web part model that provides full support for client-side SharePoint development, easy integration with SharePoint data and support for open source tooling. With the SharePoint Framework, you can use modern web technologies and tools in your preferred development environment to build productive experiences and apps in SharePoint.

In this article, we will see how to set up the environment for getting started with development using SharePoint Framework and create client web parts using the new development model. The article is classified into 3 major sections :

  • Set up SharePoint Framework Development Environment
  • Create first Hello World Client Web part using Type Script
  • Create SharePoint Framework Web part to Retrieve and Display SharePoint List Items as shown below :
          SharePoint

Set up SharePoint Framework Development Environment


Let us see how to set up the development environment so that we can kick start with SharePoint Framework development. Below are the required components that we will have to install in the environment.
  • Node JS
  • Yeoman and Gulp
  • Yeoman SharePoint Generator
  • Code Editor(Visual Studio Code/Webstorm)
  • Postman and Fiddler(optional)

Install Node JS




Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world. We will be making use of npm along with Yeoman and Gulp to package and deploy modules.

As the first step we will install NodeJS Long Term Support Version (LTS). We can install Node JS from this link.


Once we have downloaded the LTS version, run the executable file and proceed.


Accept the license agreement and click on Next.


We will select Node.js run time installation.


Click on Install to start the installation procedure.


Finally we are done installing NodeJS.


Click on Finish button and restart your computer. You won’t be able to run Node.js until you restart your computer.

If we run the NodeJS command prompt, we will get the message as shown below. Thus, the Node JS has been successfully installed in the local machine.


Now, let’s see the version of Node Package Manager (npm) by running the command npm –v . It is running V3 version.




Install Yeoman and Gulp





Yeoman is a scaffolding tool for modern web apps. It helps you to kick-start new projects, prescribing best practices and tools to help you stay productive. Often called Yo, it scaffolds out a new application, writing your build configuration (e.g Gulpfile) and pulling in relevant build tasks and package manager dependencies (e.g npm) that you might need for your build.

Gulp is a JavaScript task runner that helps us automate common tasks like refreshing your browser when you save a file, Bundling and minifying libraries and CSS, Copying modified files to an output directory etc. We will be using Yo and Gulp together for creating SharePoint Client Webparts.

Now, let’s install Yeoman and Gulp simultaneously by running the below command:

npm install -g yo gulp


We can get the version of Yeoman using the command:

yo --version


We can get the Gulp Version using the command:

gulp –v



↑ Return to Top




Install Yeoman SharePoint Generator

The Yeoman SharePoint web part generator helps you to quickly create a SharePoint client-side solution project with the right tool chain and project structure.

Yeoman SharePoint Generator can be installed using the below command:

npm install -g @microsoft/generator-sharepoint@latest


We can get the version of Yeoman Generator by running the below command. As we can see 1.0.0 indicates General Availability version.

npm view @microsoft/generator-sharepoint version




Code Editor

Next, we need a code editor that will help us with code editing. We can use any code editor or IDE that supports client-side development to build our web part, such as:

  • Visual Studio Code
  • Atom
  • Webstorm

We will use Visual Studio Code in this walkthrough. You can get it from here.


Once we have downloaded the exe, proceed with the installation.


Click on Install to start the installation procedure.


Finally, we have completed installation of the Visual Studio Code editor.


Sample Screen Shot,



↑ Return to Top




Additional Tools for Development and Debugging

Once we start the development, we will have to debug or test the application. Fiddler and Postman can help us in this task.


Fiddler

Fiddler is an HTTP debugging proxy server application. It captures HTTP and HTTPS traffic and logs it for the user to review. You can get fiddler from here


Once the executable has been downloaded. Click on Install to set up Fiddler in your local machine.


Using fiddler, we can examine the traffic as it is being sent or received.



Postman

Postman can be used to test SharePoint’s REST service endpoints and verify the returned data and request headers. We can get Postman from here


Postman can be added to Chrome as an app.


The REST url can be entered in the Request URL field and we can click on Send to get the SharePoint data.


Thus, we saw how to set up the environment and now we are ready to get started with the new SharePoint Framework development model.

↑ Return to Top



Create the First Hello World Client Web part

In this section, we will see how to create and deploy the first client web part using SharePoint Framework.We will be creating a Hello World client web part to understand the project structure and testing procedure.


Create the Web part project

Before moving forward, ensure that the SharePoint Framework development environment is ready. Spin up Node.js command prompt using which we will be creating the web part project structure.

We can create the directory where we would be adding the solution using the below command:

md ClientWebPart-HelloWorld

Let’s move to the newly created working directory using the command:

cd ClientWebPart-HelloWorld



We will then create the client web part by running the Yeoman SharePoint Generator:

yo @microsoft/sharepoint



This will display the prompt which we will have to fill up so as to proceed with project creation,

  • What is your solution name? : Accept the default client-web-part-hello-world as your solution name and choose Enter.
  • Where do you want to place your files : Use Current Folder
  • What framework would you like to start with : Select “No javaScript web framework” for the time being as this is a sample web part

  • What is your webpart name : Go on and press enter to accept the default Web part name as HelloWorld
  • Go on and press enter to accept the default Web part description as HelloWorld description

Yeoman has started working on the scaffolding of the project. It will install the required dependencies and scaffold the solution files for the HelloWorld web part which will take some time to complete. Once completed, we will get a Congratulations message.



↑ Return to Top




Test the web part

So as to test the client web part, we can build and run it on the local web server where we are developing the web part. SharePoint Framework development uses HTTPS endpoint by default. Since a default certificate is not configured for the local development environment, our browser will report a certificate error. The SharePoint Framework tool chain comes with a developer certificate that we can install for testing client web parts locally. From the current web part directory, run the below command:

gulp trust-dev-cert




Click on Yes to install the certificate.


Now, let’s preview the web part by running the gulp serve command. This command will execute a series of gulp tasks and will create a Node-based HTTPS server at 'localhost:4321'. It will then open the browser and display the client web part.


SharePoint Workbench

SharePoint Workbench is a developer design surface that enables us to test the developed client web parts without deploying them directly to SharePoint. It provides a client-side page to which we can add the created web parts.

Thus the SharePoint Workbench has opened up in the browser but there are no visible web parts. So let’s go ahead and click on the Plus sign.

It will give us the option to add the Hello World web part that we have created recently.

On clicking it, the web part will be added to the page. The web part contains few custom messages.

We can edit the description property directly from the UI as shown below. However if we want to edit this web part to add more details and functionality, we will have to go back and terminate the gulp server command. 

To stop Gulp from listening to the process we can press ‘Control + C’ . This will terminate the Gulp Serve command and stop the server.



↑ Return to Top




Edit the web part

Now, let’s try to edit the web part and add more functionality to it. To do that, navigate to ‘src\webparts\helloWorld’ location.

Run ‘Code .’ in the console which will open up the Visual Studio Code editor window.

In the left pane of Visual Studio Code, we can see the project structure. The bulk of the logic resides within the HelloWorldWebPart.ts file. Let’s add JavaScript code to alert a message within this typescript file.

On clicking save Gulp will rebuild the web part project as shown below.

Again running ‘gulp serve’ will display the updated web part in the browser. This time it will display the alert message as well.


Add the web part to SharePoint

So far we were testing the web part in SharePoint Workbench locally, now let’s try to test it within the SharePoint Context. SharePoint Workbench is also hosted in SharePoint Online to preview the web part. It can be accessed by adding ‘ _layouts/15/workbench.aspx’ to the SharePoint Online URL.

Expand the Plus sign and add the Hello World web part.

The web part has triggered the alert message in the page indicating successful hosting of the web part within SharePoint.

Thus, we saw how to create a client web part using SharePoint Framework and test it within SharePoint.

↑ Return to Top



Create SharePoint Framework Client Web Part to Retrieve and Display List Items

In this section, we will be creating a client Web part, which will be retrieving the list items from SharePoint List (EmployeeList) and will display it in the tabular form in the client Web part, as shown below.

SharePoint


Create the Web part Project


Spin up Node.js command prompt, using which we will be creating the Web part project structure.

SharePoint

This will open up the console where we can create the SharePoint Framework project structure.

SharePoint

We can create the directory, where we will be adding the solution, using the command given below.

md GetSharePointListItems

Let’s move to the newly created working directory, using the command.

cd GetSharePointListItems


SharePoint

We will then create the client Web part by running the Yeoman SharePoint Generator.

yo @microsoft/sharepoint


SharePoint

This will display the prompt, which we will have to fill up, so as to proceed with the project creation.

  • What is your solution name? : Set it to ‘GetSPListItems’.

On pressing enter, we will be asked to chose the working folder for the project.

SharePoint

  • Where do you want to place your files- Use current folder.
  • What framework would you like to start with- Select “No javaScript web framework” for the time being, as this is a sample Web part.
  • What is your Webpart name- We will specify it as ‘GetSPListItems’ and press Enter
  • What is your Webpart description- We will specify it as this Webpart will retrieve the list items from SharePoint list and display in a table.

    SharePoint

Yeoman has started working on the scaffolding of the project. It will install the required dependencies and scaffold the solution files for the ‘GetListItems’ Web part, which will take some time to complete. Once completed, we will get a congratulations message.

SharePoint

↑ Return to Top




Test the Web part locally

In order to test the client Web part, we can build and run it on the local Web Server, where we are developing the Web part. SharePoint Framework development uses HTTPS endpoint by default. Since a default certificate is not configured for the local development environment, our Browser will report a certificate error. SharePoint Framework tool chain comes with a developer certificate, which we can install for testing the client Web parts locally. From the current Web part directory, run the command given below.

gulp trust-dev-cert


SharePoint

Now, let’s preview the Web part by running the gulp serve command.

SharePoint

This command will execute a series of gulp tasks and will create a Node-based HTTPS Server at 'localhost:4321'. It will then open the Browser and display the client Web part.

SharePoint

This indicates that the project structure is set up correctly. We will now open up the solution in Visual Studio Code to add the logic to retrieve the list items from SharePoint and display it as a table in this page.

SharePoint

To stop Gulp from listening to the process, we can press ‘Control + C’ . This will terminate the Gulp Serve command and stop the Server.

↑ Return to Top



Edit the web part

Now let’s try to edit the web part and add more functionality to it. To do that navigate to “src\webparts\getSpListItems” location.

SharePoint

In the left pane of Visual Studio Code, we can see the project structure. The bulk of the logic resides within the GetSPListItemsWebPart.ts file. Let’s add the code to retrieve SharePoint list items from the Employee List within this TypeScript file.

SharePoint


Define List Model



Since we want to retrieve an Employee list items data, we will be creating list model with SharePoint list fields in the GetListItemsWebPart.TS file, as shown below. Place it above the ‘GetSpListItemsWebPart’ class. 

 
export interface ISPLists { 
    value: ISPList[]; 
  
export interface ISPList { 
    EmployeeId: string; 
    EmployeeName: string; 
    Experience: string; 
    Location: string; 
  }

↑ Return to Top




Create Mock HTTPClient to test data locally

In order to test the list item retrieval in the local workbench, we will create a mock store, which returns mock Employee list data. We will create a new file inside ‘src\webparts\ getSpListItems’ folder named MockHttpClient.ts, as shown below.

SharePoint

We will then copy the code given below into MockHttpClient.ts, as shown below. 

import { ISPList } from './GetSpListItemsWebPart'
   
export default class MockHttpClient { 
    private static _items: ISPList[] = [{ EmployeeId: 'E123', EmployeeName: 'John', Experience: 'SharePoint',Location: 'India' },]; 
    public static get(restUrl: string, options?: any): Promise<ISPList[]> { 
      return new Promise<ISPList[]>((resolve) => { 
            resolve(MockHttpClient._items); 
        }); 
    
}

SharePoint

We can now use the MockHttpClient class in the ‘GetSPListItems’ class. Let’s import the ‘MockHttpClient’ module by going to the GetSpLitItemsWebPart.ts and pasting the line given below just after “import { IGetSpListItemsWebPartProps } from './IGetSpListItemsWebPartProps';” 

import MockHttpClient from './MockHttpClient';

We will also add the mock list item retrieval method within the ‘GetSpListItemsWebPart’ class. 

private _getMockListData(): Promise<ISPLists> { 
    return MockHttpClient.get(this.context.pageContext.web.absoluteUrl).then(() => { 
        const listData: ISPLists = { 
            value: 
            
                { EmployeeId: 'E123', EmployeeName: 'John', Experience: 'SharePoint',Location: 'India' }, 
                 { EmployeeId: 'E567', EmployeeName: 'Martin', Experience: '.NET',Location: 'Qatar' }, 
                { EmployeeId: 'E367', EmployeeName: 'Luke', Experience: 'JAVA',Location: 'UK'
            
            }; 
        return listData; 
    }) as Promise<ISPLists>; 
}


Retrieve SharePoint List Items

SharePoint Framework has the helper class spHttpClient, which can be utilized to call REST API requests against SharePoint. We will use REST API: “/_api/web/lists/GetByTitle('EmployeeList')/Items” to get the list items from SharePoint List.

To use ‘spHttpClient’, we will first have to import it from the ‘@microsoft/sp-http’ module. We will import this module by placing the line given below after the mockHttpClient import code -“import MockHttpClient from './MockHttpClient';” 

import { 
  SPHttpClient 
} from '@microsoft/sp-http';
 

We will be then adding the method given below to get SharePoint list items, using REST API within the ‘GetSpListItemsWebPart’ class. 

private _getListData(): Promise<ISPLists> { 
return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle('EmployeeList')/Items`, SPHttpClient.configurations.v1) 
    .then((response: Response) => {  
      debugger; 
      return response.json(); 
    }); 
}


↑ Return to Top




Render the SharePoint List Items From Employee List

Once we run the gulp serve command, we can test the Web part in SharePoint Workbench in the local environment or using SharePoint Online Context. SharePoint Framework uses ‘EnvironmentType’ module to identify the environment, where the Web part is executed.

In order to implement this, we will import ‘Environment’ and the ‘EnvironmentType’ modules from the @microsoft/sp-core-library bundle by placing it at the top of the GetSpListItemsWebpart.ts file. 

import { 
  Environment, 
  EnvironmentType 
} from '@microsoft/sp-core-library';

We will then check Environment.type value and if it is equal to Environment.Local, the MockHttpClient method, which returns dummy data which will be called else the method that calls REST API is able to retrieve SharePoint list items will be called. 

private _renderListAsync(): void { 
       
    if (Environment.type === EnvironmentType.Local) { 
      this._getMockListData().then((response) => { 
        this._renderList(response.value); 
      }); 
    
     else
       this._getListData() 
      .then((response) => { 
        this._renderList(response.value); 
      }); 
   
}

Finally, we will add the method given below, which will create HTML table out of the retrieved SharePoint list items. 

private _renderList(items: ISPList[]): void { 
  let html: string = '<table class="TFtable" border=1 width=100% style="border-collapse: collapse;">'
  html += `<th>EmployeeId</th><th>EmployeeName</th><th>Experience</th><th>Location</th>`; 
  items.forEach((item: ISPList) => { 
    html += ` 
         <tr> 
        <td>${item.EmployeeId}</td> 
        <td>${item.EmployeeName}</td> 
        <td>${item.Experience}</td> 
        <td>${item.Location}</td> 
        </tr> 
        `; 
  }); 
  html += `</table>`; 
  const listContainer: Element = this.domElement.querySelector('#spListContainer'); 
  listContainer.innerHTML = html; 
}

To enable rendering of the list items given above, we will replace Render method in the ‘GetSpListItemsWebPart’ class with the code given below. 

public render(): void { 
     this.domElement.innerHTML = ` 
     <div class="${styles.helloWorld}"
  <div class="${styles.container}"
    <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}"
      <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1"
        <span class="ms-font-xl ms-fontColor-white" style="font-size:28px">Welcome to SharePoint Framework Development</span> 
           
        <p class="ms-font-l ms-fontColor-white" style="text-align: center">Demo : Retrieve Employee Data from SharePoint List</p> 
      </div> 
    </div> 
    <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}"
    <div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-size:18px;">Employee Details</div> 
    <br> 
<div id="spListContainer" /> 
    </div> 
  </div> 
</div>`; 
this._renderListAsync(); 
  }


Test the Web part in local SharePoint Workbench

Now,  we can see the output generated in the local SharePoint Workbench.

SharePoint

Since the environment is local, the mock data has been used to generate the table, as shown below.

SharePoint

Thus, we have successfully tested the client Web part locally.

↑ Return to Top



Test the Web part in SharePoint Online

Now, let’s test the Web part in SharePoint Workbench available in SharePoint Online. This time, the 'EnvironmentType' check will evaluate to SharePoint and REST API endpoint method will be called to retrieve the list items from SharePoint list. SharePoint Online list EmployeesList to which we are trying to connect, using REST API is given below.

SharePoint

Once we have login in to SharePoint Online, we can invoke the workbench by appending the text ‘_layouts/15/workbench.aspx’ to SharePoint Online URL. As we can see below, the items have been successfully retrieved, using REST API and the data has been built into HTML table in the client Web part.

SharePoint

We can further modify the CSS by making changes in the ‘GetSpListItems.module.scss’ file.

SharePoint

The Type Script solution file has been zipped and uploaded here . Feel free to work on it.


Summary

Thus, we have successfully retrieved the list items from SharePoint List ‘EmployeeList’, using REST endpoint and have displayed it in tabular form in SharePoint Framework Client Web part.


Reference