Skip to content
This repository was archived by the owner on Aug 28, 2024. It is now read-only.

Using sp pnp js in SharePoint Framework

Patrick Rodgers edited this page Feb 22, 2017 · 4 revisions

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

SharePoint Framework makes use of the uglifyjs library when solutions are packaged using the --ship flag. Unfortunately uglifyjs does not support es6 syntax so you will need to mark the sp-pnp-js library as an external as described on the deployment page.

Clone this wiki locally