Thursday, 7 November 2019

SPFx general code review points

Recently our client want to code review with Microsoft. We were not sure what can we implement in SPFx. Below were few suggestions after our code review:

1. Do not import * from name space

For this you need to make change in tsconfig.json file. Add compiler option - "allowSyntheticDefaultImports": true. Then you will able to make below change

For example, import * as React from 'react'; should be import React from 'react';

2. Delete unused reference, variables and commented code.

3. Use escape for string property values in tsx

you need to load below name space
import { escape } from '@microsoft/sp-lodash-subset';

Then for sting values use it with escape.
For example, any string property when you use in tsx, instead using -  this.props.scopeType
use it like -  escape(this.props.scopeType);

4. Remove for loops where possible.

For example in below scenario, you can push the whole array instead looping through each item.
for (var j = 0; j < projectTask.length; j++) {
Can be done as

5. Use global varible for hardcoded values

For example, use variable to store site url and replace that with variable name
fetchUrl = "https:/'Projects')/items?$filter=" + filterQuery + "&$top=4999&$select=Title";

could be
var projectCenterURL = "";

fetchUrl = projectCenterURL+"/_api/web/lists/GetByTitle('Projects')/items?$filter=" + filterQuery + "&$top=4999&$select=Title";

6. use console log for values instead alert
private _onItemInvoked(item: any): void {
    alert(`Item invoked: ${item.ID}`);

7. Move common methods to common file to improve code re-usability.

8. Use switch case instead of multiple if else statement

9. Enable public CDN and load CSS/ Js files from there.

10. You can make a single fetch api call in common and reuse it instead of writing code again:

fetch(URL, {
        method: 'GET',
        mode: 'cors',
        credentials: "include",     
        headers: new Headers({
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Cache-Control': 'no-cache',
            'pragma': 'no-cache',
    }).then(async(response) => await response.json())
    .then(async(data)=> {
       return data;

No comments:

Post a Comment