Using sp pnp js in SharePoint Framework - SharePoint/PnP-JS-Core GitHub Wiki

The JS Core library was built to work seamlessly with the SharePoint Framework but there are a few things to keep in mind. The functionality described in this article is available in version 2.0.1 of the library or later.

Establish Context

In classic pages we make use of the _spContextPageInfo global variable to ensure we are making requests to the correct web. This variable or an equivalent global value does not exist in SPFx or modern sites & pages - so we have to supply the context to the library. This can be done in several ways - each of which accomplishes the same outcome.

You can supply the context directly to sp-pnp-js and we'll take care of the remainder of the configuration. Just add the below snippet to your SPFx webpart, or update your onInit method if you have already have an override.

import pnp from "sp-pnp-js";

// ...

public onInit(): Promise<void> {

  return super.onInit().then(_ => {

    pnp.setup({
      spfxContext: this.context
    });
    
  });
}

The other way you can ensure you are calling to the correct web is to instantiate the web object directly and pass in the url as shown below. This method is slightly more flexible as you are not setting the base url for all calls, but you must do it each time.

import { Web } from "sp-pnp-js";

// ...

public render(): void {

  let web = new Web(this.context.pageContext.web.absoluteUrl);

  web.select("Title").getAs<{ Title: string }>().then(w => {

    this.domElement.innerHTML = `Web Title: ${w.Title}`;
  });
}

Production Deployment

It is recommended that you make use of a CDN when deploying to production, but not required. This will shrink the size of your solution package and allow you to use the library across web parts without incurring the penalty of loading the file multiple times from within a bundle. You can find details on the deployment page.

⚠️ **GitHub.com Fallback** ⚠️