What is SharePoint PnP? Why should I consider it?
On 3 minutesSharePoint Patterns and Practices (PnP) is an initiative aimed at presenting a standard patterns and practices for working with SharePoint. It contains a library of PowerShell commands (PnP PowerShell), .Net and JavaScript that allows you to perform complex provisioning and artifact management actions towards SharePoint.
In a nutshell, it reduces the amount of code you write. PnP is essentially, a trimmed version of the Client Side Object Model (CSOM) and the JavaScript Object Model (JSOM) libraries.
It contains a fluent API for working with the full SharePoint REST API as well as utility and helper functions.
This series will focus on the PnP JavaScript library.
When working with SharePoint using JavaScript, you will traditionally use JSOM or REST approach. So the question is, if I can do almost everything using these two approaches, why should I consider PnP JS?.
To answer this question, I will use an example to illustrate why PnP is better.
Our examples will display the title and description of a specified website using the three approaches.
SharePoint JavaScript Object Model
//include jQuery file in the SharePoint page
var scriptbase = hostweburl + "/_layouts/15/";
// Load the js files and continue to
// the execOperation function.
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js", execOperation);
}
);
function execOperation(){
var clientContext = new SP.ClientContext(siteUrl);
var oWebsite = clientContext.get_web();
clientContext.load(oWebsite);
clientContext.executeQueryAsync(
function(){
console.log('Title: ' + oWebsite.get_title() + ' Description: ' + oWebsite.get_description());
},
function(sender,args){
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
);
}
When SharePoint JSOM was introduced, it was the first step towards supporting client-side solutions on SharePoint. However, it is no longer being actively maintained and might not offer access to all capabilities available through the REST API.
SharePoint REST API
//include jQuery file in the SharePoint page
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web?$select=Title,Description",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
console.log("Title: " + data.d.Title + " Description: " + data.d.Description);
}
});
PnP JS
//include pnp file in the SharePoint page
pnp.sp.web.select("Title.Description").get()
.then(function(data){
console.log('Title: ' + data.Title + ' Description: ' + data.Description);
})
.catch(function(err){
console.log(err);
});
Conclusion
Looking at the code samples above, you can clearly see that the PnP JS version is less verbose. It will make your code base light and easy to work with.
References
https://github.com/SharePoint/PnP-JS-Core/wiki
Other posts in this series
- What is SharePoint PnP? Why should I consider it?