Lets see how to use Typescript and System Js with PNP JS Core in SharePoint Hosted App / Add-in in this blog post. To begin with, lets add reference to typed definitions of fetch and es6-promise modules to enable intellisense to VS Code.
Typings/DefinitelyTyped for PNP
The typescript allows us to have the declaration files which helps us to know the shape of the code by referencing the related files. It is used for the development purpose to check the error on compile time for the types. As we need to include the below files for our project.
· Promise.d.ts
Pnp.d.ts
class Employee {
public Title: string;
public Name: string;
public Designation: string;
}
Employee.ts is the model for the SharePoint list.
App.ts
import pnp from 'pnp' //importing the package PNP
class app
{
private lstEmployees: Array<Employee>;
private appWebUrl: string;
private hostWebUrl: string;
constructor() {
this.appWebUrl = this.getUrlParamByName("SPAppWebUrl");
this.hostWebUrl = this.getUrlParamByName("SPHostUrl");
this.getListItems(this.appWebUrl, this.hostWebUrl);
}
private getUrlParamByName(name): string {
name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
var regex = new RegExp("[\?&]" + name + "=([^]*)");
var results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/+/g, " "));
}
private getListItems(appWebUrl,hostWeburl): void
{
pnp.sp.crossDomainWeb(appWebUrl, hostWeburl).lists.getByTitle('Test').items.get().then(data => {
this.lstEmployees = data;
var table = <HTMLTableElement> document.getElementById('empData');
for (let employee of this.lstEmployees) {
var tableRow = table.insertRow(table.rows.length);
tableRow.insertCell(0).innerHTML = employee.Title;
tableRow.insertCell(1).innerHTML = employee.Name;
tableRow.insertCell(2).innerHTML = employee.Designation;
}
}).catch(function (error) {
alert('error');
console.log(error);
});
}
}
export =new app();
Default.aspx
[Code 3]
<script src="../Scripts/Reflect.js"></script>
<script src="../Scripts/system.src.js"></script>
<script src="../Scripts/fetch.js"></script>
<script src="../Scripts/es6-promise.min.js"></script>
<script src="../Scripts/pnp.js"></script>
<script>
System.config({
map: {
app: 'app', //app folder name
'pnp': '../Scripts/pnp.js' //Refer the package PNP from this specific file, as pnp.d.ts will not available in the deployment.
},
packages: {
app: {
main: 'app.js',
defaultExtension: 'js'
}
}
});
System.import('app').catch(function(err){ console.error(err); });
</script>
<div>
<table id="empData">
<tr>
<th>Title</th>
<th>Name</th>
<th>Designation</th>
</tr>
</table>
Leave a comment