Bulk Publishing FIles in SPFX

Introduction

 
Publishing bulk files is a difficult task to do manually. In this article, I have automated files to check-in and publish using batch calls (reduce the number of calls).
 

Steps 

 
Open a command prompt and create a directory for the SPFx solution.
 
md spfx-Bulkpublishing
 
Navigate to the above-created directory.
 
cd spfx-Bulkpublishing
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 
Solution Name
 
Hit Enter for the default name (spfx-Bulkpublishing in this case) or type in any other name for your solution.
Selected choice - Hit Enter
 
Target for the component
 
Here, we can select the target environment where we are planning to deploy the client web part; i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice - SharePoint Online only (latest).
 
Place of files
 
We may choose to use the same folder or create a subfolder for our solution.
Selected choice - same folder.
 
Deployment option
 
Selecting Y will allow the app to be deployed instantly to all sites and be accessible everywhere.
Selected choice - N (install on each site explicitly).
 
Permissions to access web APIs
 
Choose if the components in the solution require permission to access web APIs that are unique and not shared with other components in the tenant.
Selected choice - N (solution contains unique permissions)
 
Type of client-side component to create
 
We can choose to create a client-side web part or an extension. Choose the web part option.
Selected choice - WebPart
 
Web part name
 
Hit Enter to select the default name or type in any other name.
Selected choice - Bulkpublishing
 
Web part description
 
Hit Enter to select the default description or type in any other value.
 
Framework to use
 
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice - React
 
The Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command:
 
npm shrinkwrap
 
In the command prompt, type the below command to open the solution in the code editor of your choice.
 
NPM Packages used:
  1. npm install @pnp/[email protected] --save  //for sharepoint operations        
  2. npm install @pnp/polyfill-ie11 --save  //for iell support   
In BulkpublishingWebPart.ts:
  1. import * as React from 'react';  
  2. import * as ReactDom from 'react-dom';  
  3. import { Version } from '@microsoft/sp-core-library';  
  4. import {  
  5.   IPropertyPaneConfiguration,  
  6.   PropertyPaneTextField  
  7. } from '@microsoft/sp-property-pane';  
  8. import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';  
  9. import * as strings from 'BulkpublishingWebPartStrings';  
  10. import Bulkpublishing from './components/Bulkpublishing';  
  11. import { IBulkpublishingProps } from './components/IBulkpublishingProps';  
  12.   
  13. export interface IBulkpublishingWebPartProps {  
  14.   description: string;  
  15.   libraryName:string;  
  16. }  
  17.   
  18. export default class BulkpublishingWebPart extends BaseClientSideWebPart <IBulkpublishingWebPartProps> {  
  19.   
  20.   public render(): void {  
  21.     const element: React.ReactElement<IBulkpublishingProps> = React.createElement(  
  22.       Bulkpublishing,  
  23.       {  
  24.         description: this.properties.description,  
  25.         LibraryName:this.properties.libraryName,  
  26.         context:this.context  
  27.       }  
  28.     );  
  29.   
  30.     ReactDom.render(element, this.domElement);  
  31.   }  
  32.   
  33.   protected onDispose(): void {  
  34.     ReactDom.unmountComponentAtNode(this.domElement);  
  35.   }  
  36.   
  37.   protected get dataVersion(): Version {  
  38.     return Version.parse('1.0');  
  39.   }  
  40. protected texboxvalidated(value:string):string {  
  41.   if(value.length==0){  
  42.   
  43.     return "Enter Library Name";  
  44.   }  
  45.    
  46.   }  
  47.   
  48.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  49.     return {  
  50.       pages: [  
  51.         {  
  52.           header: {  
  53.             description: strings.PropertyPaneDescription  
  54.           },  
  55.           groups: [  
  56.             {  
  57.               groupName: strings.BasicGroupName,  
  58.               groupFields: [  
  59.                 PropertyPaneTextField('libraryName', {  
  60.                   label: 'LibraryName',  
  61.                   multiline:false,  
  62.                   resizable:false,  
  63.                   onGetErrorMessage:this.texboxvalidated,  
  64.                   placeholder:"please enter list name"  
  65.                 }),  
  66.                 PropertyPaneTextField('description', {  
  67.                   label: strings.DescriptionFieldLabel  
  68.                 })  
  69.               ]  
  70.             }  
  71.           ]  
  72.         }  
  73.       ]  
  74.     };  
  75.   }  

 In IBulkpublishingProps.ts:
  1. import { WebPartContext } from "@microsoft/sp-webpart-base";  
  2.   
  3. export interface IBulkpublishingProps {  
  4.   description: string;  
  5.   LibraryName:string;  
  6.   context:WebPartContext;  

In Bulkpublishing.tsx:
  1. import * as React from 'react';  
  2. import { IBulkpublishingProps } from './IBulkpublishingProps';  
  3. import "@pnp/polyfill-ie11";   
  4. import {sp} from "@pnp/sp/presets/all";  
  5. export default class Bulkpublishing extends React.Component<IBulkpublishingProps, {}> {  
  6.   constructor(props: IBulkpublishingProps) {        
  7.     super(props);        
  8.     sp.setup({      
  9.       spfxContext:this.props.context,      
  10.       sp: {      
  11.           headers: {      
  12.             "Accept""application/json; odata=verbose"      
  13.           }      
  14.         },      
  15.        ie11: true         
  16.   });       
  17.   this.BulkPublishingFiles=this.BulkPublishingFiles.bind(this);     
  18.     }  
  19.   
  20.     private BulkPublishingFiles=async(e)=>{  
  21.       e.preventDefault();  
  22.       e.stopPropagation();  
  23.       e.nativeEvent.stopImmediatePropagation();  
  24.       console.log(e);  
  25.       let library = await sp.web.lists.getByTitle(this.props.LibraryName);  
  26.        library.items.expand("Folder""File").getAll().then((items) => {  
  27.   const batch = sp.createBatch();  
  28.   items.forEach(async item => {  
  29.     if(item["File"]){  
  30.     if(item["File"]["CheckOutType"]==0){  
  31.        await sp.web.getFileByServerRelativeUrl(item.File.ServerRelativeUrl).checkin();  
  32.     }  
  33.       
  34.      await sp.web.getFileByServerRelativeUrl(item.File.ServerRelativeUrl).inBatch(batch).publish();  
  35. console.log( "Processing..." + " "  +item.File.ServerRelativeUrl);}  
  36.   });  
  37.   batch.execute().then(() => {  
  38.     console.log('All done!');  
  39.   }).catch(console.log);  
  40. });  
  41.     }  
  42.   public render(): React.ReactElement<IBulkpublishingProps> {  
  43.     return (  
  44.       <div>  
  45.     <button onClick={this.BulkPublishingFiles}> Publish Files</button>   
  46.       </div>  
  47.     );  
  48.   }  

Expected Output:
 
 
Since I used the batch operation concept in this webpart, it reduces the number of calls to Sharepoint (throttling error 429 minimized).
 

Conclusion

 
In this article, we learned how to bulk publish files from the document library using pnpjs. I hope this helps someone. Happy coding :)