PnP – Patterns & Practices Libraries

 

@pnp/sp

The @pnp/sp package provides the PnP JS library access to SharePoint via the context of either the webpart or extension that is running the library.

V3 of the library brought in a number of breaking changes which can be resolved using the methods below:

New SPFI class

With V3 the way we call and obtain access to the SharePoint rest services has changed significantly which means certain adaptations will need to be made to how we implement this library in our code base.

There are three main ways this can be done:

1. manually passing the SPFx context between components and use this to dynamically create the SP object per call as and when needed (resource internsive and difficult to use when adding non-class based components to provider helper services)

2. Create the SP object on init and pass this through a property to each component so it can be called when needed (resource intensive)

3. Create a configuration file that declares a variable which is accessible to all components within the application - this is the preffered method

Declare SP globally

Full details of this method can be found here https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/guidance/use-sp-pnp-js-with-spfx-web-parts

Create config file

 

Create a file named pnpjsConfig.ts within the top level of the src folder in the SPFx solution, this will allow it to be called in both Webpart and Extension components and then copy in the below code:

Update Entry File

Update the entry file of the application and add an import for the above new file, for example if using an Extension component the following import would be used:

Update OnInit of Entry File

Update the OnInit function within the entry file of the application and add the following:

Use within React components

Within any React linked components you can call the sp object simply by doing the following:

Use within non-React components

You can now use our newly created _sp object to make all our REST calls via PnP JS, below is an example using a helper module that has a constant object setup with a number of different function calls which will all use the _sp object to make the calls to the SharePoint REST Api: