Share via


SharePoint Framework (SPFx): Optimize Your Solutions

Overview

SharePoint Framework (SPFx) has become popular in a short span of time and has been widely adopted. SPFx is being developed using modern toolchain and client technologies, and helps to deliver the functionality faster. However, when we are using variety and a large number of web parts on a site, we always need to think of the overall performance and optimization techniques.

 

Common problems with solution development

  1. Poor architecture
  2. Less thinking about the impact on tenant
  3. Heavy packages bundling all assets together
  4. Referencing 3rd party libraries
  5. Developers interest

Due to one or more of the above points, optimization of SPFx solutions take a lower priority. Here are a few common observations and suggestions to optimize SPFx solutions.

 

Tip #1: Split multiple web parts to load individually

A single SPFx solution can have multiple web parts or extensions. All of these are typically referenced in config/config.json file as below.

{  
  "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",  
  "version": "2.0",  
  "bundles": {  
      "my-spfx": {  
          "components": [  
              {  
                  "entrypoint": "./lib/webparts/webpart1/webpart1.js",  
                  "manifest": "./src/webparts/webpart 1/webpart1.manifest.json" 
              },  
              {  
                  "entrypoint": "./lib/webparts/webpart2/webpart2.js",  
                  "manifest": "./src/webparts/webpart2/webpart2.manifest.json" 
              }  
          ]  
      }  
  },  
  "externals": {},  
  "localizedResources": {}  
}

Both web parts get bundled in one single JavaScript file. This situation has the below points to consider.

  • When a single web part is added to a page, actually both are loaded.
  • If both the web parts are on one page, this will reduce the load time.

It is better to split both the web parts in separate files to reduce what is loaded on the page.

{  
  "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",  
  "version": "2.0",  
  "bundles": {  
      "my-spfx-1": {  
          "components": [  
              {  
                  "entrypoint": "./lib/webparts/webpart1/webpart1.js",  
                  "manifest": "./src/webparts/webpart1/webpart1.manifest.json" 
              }  
          ]  
      },  
      "my-spfx-2": {  
          "components": [  
              {  
                  "entrypoint": "./lib/webparts/webpart2/webpart2.js",  
                  "manifest": "./src/webparts/webpart2/webpart2.manifest.json" 
              }  
          ]  
      }  
  },  
  "externals": {},  
  "localizedResources": {}  
}

Tip #2: Load third party libraries dynamically

SharePoint Framework uses a webpack to bundle the solution. Webpack allows the dynamic import of part of an application. Consider an example of Moment library used in our SPFx web part to manage date operations.
 

Normal import

In the below example, Moment library will be included in the final package, irrespective of whether GetLongTime is called or not.

// Import moment as a dependency  
import * as moment from moment  
    .  
    .  
export default  class DateTimeClass {  
  public GetLongTime(dateTime:string){  
      return moment(dateTime).format("LLLL");  
  }  
}

Dynamic import

In the below example, Moment library is loaded asynchronously only when the GetLongTime function is called. 

export default  class DateTimeClass {  
  public async GetLongTime(dateTime:string){  
      const moment = await import(  
          /* webpackChunkName: 'my-moment' */ 
          'moment' 
      );  
      return moment(dateTime).format("LLLL");  
  }  
}

Tip #3: Reference external libraries externally

We often use external libraries (e.g. jQuery) in our SPFx web part. Adding these external libraries as npm packages, and including them inside the final package, making it bulky. The external libraries can be referenced externally as below,

  1. Under the config folder, open the config.json file.
  2. To load jQuery from CDN location, add an entry to the externals section.
{  
  "entries": [  
      {  
          "entry": "./lib/webparts/helloWorld/HelloWorldWebPart.js",  
          "manifest": "./src/webparts/helloWorld/HelloWorldWebPart.manifest.json",  
          "outputPath": "./dist/helloworld.bundle.js" 
      }  
  ],  
  "externals": {  
      "@microsoft/sp-client-base": "node_modules/@microsoft/sp-client-base/dist/sp-client-base.js",  
      "@microsoft/sp-client-preview": "node_modules/@microsoft/sp-client-preview/dist/sp-client-preview.js",  
      "@microsoft/sp-lodash-subset": "node_modules/@microsoft/sp-lodash-subset/dist/sp-lodash-subset.js",  
      "jquery": "https://code.jquery.com/jquery-3.1.0.min.js" 
  },  
  "localizedResources": {  
      "helloWorldStrings": "webparts/helloWorld/loc/{locale}.js" 
  }  
}

Import jQuery in SPFx web part as below:

import * as $ from 'jquery';

Tip #4: Analyzing your bundle

Extend the Webpack configuration in your SPFx project to understand the bundle.

Run the below command to install the webpack-bundle-analyzer package to your SPFx solution.

npm install webpack-bundle-analyzer --save-dev

Update the contents of the gulpfile.js file as below:

     
'use strict'; 
 
const gulp = require('gulp');  
const path = require('path');  
const build = require('@microsoft/sp-build-web');  
const bundleAnalyzer = require('webpack-bundle-analyzer');  
   
build.configureWebpack.mergeConfig({  
  additionalConfiguration: (generatedConfiguration) => {  
      const lastDirName = path.basename(__dirname);  
      const dropPath = path.join(__dirname, 'temp', 'stats');  
      generatedConfiguration.plugins.push(new bundleAnalyzer.BundleAnalyzerPlugin({  
          openAnalyzer: false,  
          analyzerMode: 'static',   
          reportFilename: path.join(dropPath, `${lastDirName}.stats.html`),  
          generateStatsFile: true,  
          statsFilename: path.join(dropPath, `${lastDirName}.stats.json`),  
          logLevel: 'error' 
  }));  
 
      return generatedConfiguration;  
  }  
});  
 
build.initialize(gulp);

The "gulp bundle" command will generate a visualization file at ./temp/stats/[solution-name].stats.html file.

Conclusion

In this article, we explored the commonly observed behaviors and optimization techniques to build better solutions in SPFx. The performance of the SPFx web part can be optimized by following simple techniques. This will help to keep the bundle size within limits and improve the overall performance.

References

See also

↑ Back to top