Dynamically Load SPFx Library Components

Overview

Library components are generally available with SPFx v1.9.1 release. The library component helps to build independently versioned and deployed code. It then can be consumed by various SPFx web parts or extensions.
In this article, we will explore how to dynamically load the library component and the benefits of dynamic loading.
 
 

Why load the Library component dynamically?

Here are a couple of points to set the stage.
  1. You import the library component to your SPFx web part or extension, but the call to library component methods never happens.
  2. When building SPFx components, any library you add to your project will be downloaded on the page you use the web part or extension on (irrespective of it is being called or not).
Importing the library component dynamically in the SPFx solution helps to handle above situations gracefully.
 
 

Implement Library Component

Follow the below steps to create a library component named spfx-library.
1. Run the Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint  
2. Yeoman generator will present you with the wizard by asking questions about the solution to be created.
 
 
3. To avoid localhost port conflicts on gulp serve, open config\serve.json and set the port to any number other than default port 4321. For more information - SharePoint Library Components – Simultaneous Parallel Development
 
  1. {  
  2.   "$schema""https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",  
  3.   "port": 4322,  
  4.   "https"true  
  5. }  
4. On the command prompt, type below command to create a local npm link to the library.
  1. npm link  
5. to run the library component (without opening a browser).
  1. gulp serve --nobrowser  
 

Implement Consumer Web Part

Let’s implement a web part named spfx-library-consumer to consume the above library component.
1. Run the Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint  
2. Yeoman generator will present you with the wizard by asking questions about the solution to be created.
 
 
3. In the command prompt, symlink a library component by running below command.
  1. npm link spfx-library  
4. Type below command to open the solution in the code editor of your choice.
  1. code .  
5. Open file src\webparts\libraryConsumer\components\LibraryConsumer.tsx.
6. Import the library component.
  1. import * as myLibrary from 'spfx-library';  
7. Refer library inside render method.
  1. public render(): React.ReactElement<ILibraryConsumerProps> {  
  2.   const myInstance = new myLibrary.CommonLibraryLibrary();  
  3.   
  4.   return (  
  5.     <div className={ styles.libraryConsumer }>  
  6.       <div className={ styles.container }>  
  7.         <div className={ styles.row }>  
  8.           <div className={ styles.column }>  
  9.             <span className={ styles.title }>Welcome to SharePoint!</span>  
  10.             <p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p>  
  11.             <p>My library: {myInstance.name()}</p>  
  12.             <p className={ styles.description }>{escape(this.props.description)}</p>  
  13.             <a href="https://aka.ms/spfx" className={ styles.button }>  
  14.               <span className={ styles.label }>Learn more</span>  
  15.             </a>  
  16.           </div>  
  17.         </div>  
  18.       </div>  
  19.     </div>  
  20.   );  
  21. }  
8. On the command prompt, run the web part solution by executing the below command.
  1. gulp serve  
9. The web part should consume the methods from the library component.
 
 
10. Open developer dashboard (F12) in the browser to see how the components are loaded.
 
 
This shows the library component is loaded by default.
 
 

Load the Library Dynamically

Consider an example, where we would like to call a method from the library component on click of a button. In this situation, the library does not require to be loaded by default, rather it should be available only when needed (on click of button, in this scenario).
Let us analyze our library loading on the calling component. Analyze the original import statement (as below).
  1. import * as myLibrary from 'spfx-library';  
Let us try to be very specific about what we need from the library component. The CommonLibraryLibrary class contains the methods in library component. The above import statement will reduce to below.
  1. import CommonLibraryLibrary from 'spfx-library';  
The old friend - webpackChunkName is helpful here, which will make sure anything in that tsx/ts file will be wrapped up in its own .js file, loaded when this line of code executes.
  1. const dynamicLibImport = await import(  
  2.       /* webpackChunkName: 'CommonLibraryLibrary' */  
  3.       'spfx-library'  
  4. );  
  5.   
  6. const myInstance = new dynamicLibImport.CommonLibraryLibrary();  
  7. alert(myInstance.name());  
The entire code for the web part component looks as below:
  1. import * as React from 'react';  
  2. import styles from './LibraryConsumer.module.scss';  
  3. import { ILibraryConsumerProps } from './ILibraryConsumerProps';  
  4. import { escape } from '@microsoft/sp-lodash-subset';  
  5. // import * as myLibrary from 'spfx-library';  
  6.   
  7. // Import Button component    
  8. import { IButtonProps, DefaultButton } from 'office-ui-fabric-react/lib/Button';  
  9. import { autobind } from 'office-ui-fabric-react';  
  10.   
  11. export default class LibraryConsumer extends React.Component<ILibraryConsumerProps, {}> {  
  12.   public render(): React.ReactElement<ILibraryConsumerProps> {  
  13.     // const myInstance = new myLibrary.CommonLibraryLibrary();  
  14.   
  15.     return (  
  16.       <div className={ styles.libraryConsumer }>  
  17.         <div className={ styles.container }>  
  18.           <div className={ styles.row }>  
  19.             <div className={ styles.column }>  
  20.               <span className={ styles.title }>Welcome to SharePoint!</span>  
  21.               <p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p>  
  22.               {/* <p>My library: {myInstance.name()}</p> */}  
  23.               <p className={ styles.description }>{escape(this.props.description)}</p>                
  24.   
  25.               <DefaultButton    
  26.                   data-automation-id="search"    
  27.                   target="_blank"    
  28.                   title="Search"    
  29.                   onClick={this._loadLibrary}    
  30.                   >    
  31.                   Load Library Component    
  32.               </DefaultButton>  
  33.             </div>  
  34.           </div>  
  35.         </div>  
  36.       </div>  
  37.     );  
  38.   }  
  39.   
  40.   @autobind  
  41.   private async _loadLibrary() {  
  42.     const dynamicLibImport = await import(  
  43.       /* webpackChunkName: 'CommonLibraryLibrary' */  
  44.       'spfx-library'  
  45.     );  
  46.   
  47.     const myInstance = new dynamicLibImport.CommonLibraryLibrary();  
  48.     alert(myInstance.name());  
  49.   }  
  50. }  
 
 

Test the library component dynamic loading

1. On the command prompt, type “gulp serve” to run the web part.
2. In the browser, open the developer dashboard (F12) to observe the component loading.
 
 
3. The page will not load the library component on the initial load.
4. Click the button “Load Library Component”. Observe the developer dashboard.
 
 
5. On the click of a button, the library component loads dynamically and executes the lines of code.
 

Summary

The library component helps to build independently versioned and deployed code. webpackChunkName is helpful to make sure anything in that tsx/ts file will be wrapped up in its own .js file, loaded when this line of code executes. Importing the library component dynamically in SPFx solution helps to optimize the overall performance.