You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/spfx/web-parts/guidance/use-sp-pnp-js-with-spfx-web-parts.md
+50-64Lines changed: 50 additions & 64 deletions
Original file line number
Diff line number
Diff line change
@@ -1,15 +1,12 @@
1
1
# Use sp-pnp-js with SharePoint Framework Web Parts
2
2
3
-
You may opt to use the [sp-pnp-js](https://www.npmjs.com/package/sp-pnp-js) library when building your SharePoint Framework web parts. This library
4
-
provides a fluent API to make building your REST queries intuitive and supports batching and caching. You can learn more on the [project's homepage](https://github.com/SharePoint/PnP-JS-Core)
5
-
which has links to documentation, samples, and other resources to help you get started.
3
+
You may opt to use the [sp-pnp-js](https://www.npmjs.com/package/sp-pnp-js) library when building your SharePoint Framework (SPFx) web parts. This library provides a fluent API to make building your REST queries intuitive and supports batching and caching. You can learn more on the [project's homepage](https://github.com/SharePoint/PnP-JS-Core) which has links to documentation, samples, and other resources to help you get started.
6
4
7
5
You can download the [full source](https://github.com/SharePoint/sp-dev-fx-webparts/tree/master/samples/knockout-sp-pnp-js) for this article from the samples site.
8
6
9
7
## Setup your Environment
10
8
11
-
Before you can complete this guide you will need to ensure you have [setup your environment](https://dev.office.com/sharepoint/docs/spfx/set-up-your-development-environment) for development
12
-
using SharePoint Framework.
9
+
Before you can complete this guide, you will need to ensure you have [setup your environment](https://dev.office.com/sharepoint/docs/spfx/set-up-your-development-environment) for development using the SharePoint Framework.
13
10
14
11
## Create a New Project
15
12
@@ -19,30 +16,30 @@ Start by creating a new folder for the project using your console of choice:
19
16
md spfx-sp-pnp-js-example
20
17
```
21
18
22
-
And enter that folder
19
+
And enter that folder:
23
20
24
21
```sh
25
22
cd spfx-sp-pnp-js-example
26
23
```
27
24
28
-
The run the Yeoman generator for SPFx
25
+
Then run the Yeoman generator for SPFx:
29
26
30
27
```sh
31
28
yo @microsoft/sharepoint
32
29
```
33
30
34
-
Enter the following values when prompted during the setup of your new project:
31
+
Enter the following values when prompted during the setup of the new project:
35
32
36
33
-**spfx-sp-pnp-js-example** as solution name (keep default)
37
34
-**Current Folder** as the solution ___location
38
-
-**Kockout** as the framework
35
+
-**Knockout** as the framework
39
36
-**SPPnPJSExample** as the name of the web part
40
37
-**Example of using sp-pnp-js within SPFx** as the description
Once the scaffolding completes open the project in your code editor of choice, the screen shots here show[Visual Studio Code](https://code.visualstudio.com/).
42
+
Once the scaffolding completes, open the project in the code editor of your choosing. The screenshots shown here demonstrate[Visual Studio Code](https://code.visualstudio.com/). To open the directory within Visual Studio Code, enter the following in the console:
46
43
47
44
```sh
48
45
code .
@@ -52,28 +49,24 @@ code .
52
49
53
50
## Install And Setup sp-pnp-js
54
51
55
-
Once your project is created you will need to install and setup sp-pnp-js, starting with installing the package. This section is common for any project type (React, etc).
52
+
Once your project is created you will need to install and setup sp-pnp-js, starting with installing the package. These steps are common for any project type (React, etc).
56
53
57
54
```sh
58
55
npm install sp-pnp-js --save
59
56
```
60
57
61
-
Because the sp-pnp-js library constructs REST requests it needs to know the URL to send these requests. When operating within classic sites and pages
62
-
we can make use of the global _spPageContextInfo variable. Within SPFx this is not available, or if it is may not be correct. So we need to rely on the
supplied by the framework. There are [two ways](https://github.com/SharePoint/PnP-JS-Core/wiki/Using-sp-pnp-js-in-SharePoint-Framework#establish-context) to ensure you have correctly setup your requests,
65
-
we'll use the onInit method in this example.
58
+
Because the sp-pnp-js library constructs REST requests it needs to know the URL to send these requests. When operating within classic sites and pages, we can make use of the global `_spPageContextInfo` variable. Within SPFx, this is not available, or if it is, may not be correct. So we need to rely on the [context](https://dev.office.com/sharepoint/reference/spfx/sp-webpart-base/iwebpartcontext) object
59
+
supplied by the framework. There are [two ways](https://github.com/SharePoint/PnP-JS-Core/wiki/Using-sp-pnp-js-in-SharePoint-Framework#establish-context) to ensure you have correctly setup your requests, we'll use the `onInit` method in this example.
66
60
67
61
### Update onInit in SpPnPjsExampleWebPart.ts
68
62
69
-
Open the src\webparts\spPnPjsExample\SpPnPjsExampleWebPart.ts file and add the import for the pnp root object.
63
+
Open the **src\webparts\spPnPjsExample\SpPnPjsExampleWebPart.ts** file and add an import statement for the pnp root object:
70
64
71
65
```TypeScript
72
66
importpnpfrom"sp-pnp-js";
73
67
```
74
68
75
-
In the onInit method update the code to appear as below. We are adding the block after the super.onInit() call. We do this after the super.onInit to ensure that the framework has a chance to initialize anything
76
-
required and that we are setting up the library after those steps are complete.
69
+
In the `onInit` method, update the code to appear as below. We are adding the block after the `super.onInit()` call. We do this after the `super.onInit` to ensure that the framework has a chance to initialize anything required and that we are setting up the library after those steps are completed.
Next you will want to replace the contents of the SpPnPjsExampleViewModel.ts file with the below. We are adding an import for the pnp items, an interface to define our list item's fields,
112
-
some observables to track both our list of items and new item form, and methods to support getting, adding, & deleting items. We also added an ensureList method which
113
-
uses the sp-pnp-js lists.ensure method to always make sure we have the list. There are many ways to provision resources but this was done to demonstrate both creating a list, field,
114
-
and items using batching in a single method.
104
+
Next, replace the contents of the **SpPnPjsExampleViewModel.ts** file with the code below. We are adding an import statement for the pnp items, an interface to define our list item's fields, some observables to track both our list of items and the new item form, and methods to support getting, adding, & deleting items. We also added an `ensureList` method which uses the sp-pnp-js `lists.ensure` method to always make sure we have the list (and to create it if necessary). There are many ways to provision resources, but this method was choosen to demonstrate creating a list, field, and items using batching within a single method.
115
105
116
-
The takeaway is that using sp-pnp-js we write much less code to handle the requests and can focus on our business logic.
106
+
The takeaway is that by using sp-pnp-js, we write much less code to handle requests and can focus on our business logic.
117
107
118
108
```TypeScript
119
109
import*askofrom'knockout';
@@ -150,12 +140,12 @@ export default class SpPnPjsExampleViewModel {
@@ -258,9 +248,9 @@ export default class SpPnPjsExampleViewModel {
258
248
OrderNumber: "75638923"
259
249
}, typeName);
260
250
261
-
//excute the batched operations
251
+
//Excute the batched operations
262
252
batch.execute().then(_=> {
263
-
//all of the items have been added within the batch
253
+
//All of the items have been added within the batch
264
254
265
255
resolve(ler.list);
266
256
@@ -282,7 +272,7 @@ export default class SpPnPjsExampleViewModel {
282
272
```
283
273
## Update the Template
284
274
285
-
Finally we need to update the template to match the functionality we have added into the ViewModel. Copy the below code into the SpPnPjsExample.template.html file. We have added a title row, a foreach repeater
275
+
Finally, we need to update the template to match the functionality we have added into the ViewModel. Copy the code below into the **SpPnPjsExample.template.html** file. We have added a title row, a foreach repeater
286
276
for the items collection, and a form allowing you to add new items to the list.
287
277
288
278
```html
@@ -344,41 +334,37 @@ for the items collection, and a form allowing you to add new items to the list.
344
334
```
345
335
## Run the Example
346
336
347
-
If you now start the sample and add then add the web part to your site's /_layouts/workbench.aspx you can see it in action.
337
+
Start the sample and add the web part to your SharePoint hosted workbench (/_layouts/workbench.aspx) to can see it in action.
348
338
349
339
```sh
350
-
gulp serve
340
+
gulp serve --nobrowser
351
341
```
352
342
353
343

354
344
355
-
You can delete existing items by clicking on the trashcan icon, or add items by putting values in both fields and clicking the add button.
345
+
You can delete existing items by clicking on the trashcan icon, or add new items by putting values in both fields and clicking the add button.
356
346
357
347
## Next Steps
358
348
359
-
The sp-pnp-js library contains a great range of functionality and extensibility. Please check out the [developer guide](https://github.com/SharePoint/PnP-JS-Core/wiki/Developer-Guide) for samples,
360
-
guidance, and hints on using and configuring the library.
349
+
The sp-pnp-js library contains a great range of functionality and extensibility. Please check out the [developer guide](https://github.com/SharePoint/PnP-JS-Core/wiki/Developer-Guide) for samples, guidance, and hints on using and configuring the library.
361
350
362
351
## Production Deployment
363
352
364
-
When you are ready to deploy your solution and want to build using the --ship flag you need to mark sp-pnp-js as an external in
365
-
the configuration. This is done by updating the SPFx config/config.js to include this line in the externals section:
353
+
When you are ready to deploy your solution and want to build using the `--ship` flag you need to mark sp-pnp-js as an external library in the configuration. This is done by updating the SPFx **config/config.js** file to include this line in the externals section:
Here we are using the public CDN but the URL can be internal or any ___location you would like to use. Be sure to update the
372
-
version number in the url to match the version you want.
359
+
In the configuration above, we are using the public CDN but the URL can be an internal path or any other ___location you would like to use. Be sure, however, to update the version number in the URL to match the version you are targeting.
373
360
374
361
## Improving the Example - Mock Data
375
362
376
-
Ideally the sample will work in both the local workbench as well as the SharePoint hosted. To enable this we need to mock our ViewModel and make an update to the web part code as outlined below.
363
+
Ideally, the sample should work within both the local workbench as well as the SharePoint hosted workbench. To enable this we need to mock our ViewModel and make an update to the web part code as outlined below.
377
364
378
365
### Mock ViewModel
379
366
380
-
Add a new file named MockSpPnPjsExampleViewModel.ts along side the other web part files, then update the content to match the below. This will provide the same set of functionality but does not
381
-
rely on SharePoint being available and will work in the local environment.
367
+
Add a new file named **MockSpPnPjsExampleViewModel.ts** alongside the other web part files. Update the content of this file using the code below. This will provide the same set of functionality but does not rely on SharePoint being available and will work in the local environment.
382
368
383
369
```TypeScript
384
370
import*askofrom'knockout';
@@ -403,20 +389,20 @@ export default class MockSpPnPjsExampleViewModel {
// When web part description is updated, change this view model's description.
392
+
// When the web part description is updated, change this view model's description.
407
393
bindings.shouter.subscribe((value:string) => {
408
394
this.description(value);
409
395
}, this, 'description');
410
396
411
-
//call the load the items
397
+
//Load the items
412
398
this.getItems().then(items=> {
413
399
414
400
this.items(items);
415
401
});
416
402
}
417
403
418
404
/**
419
-
* Gets the items from the list
405
+
* Simulates getting the items from the list
420
406
*/
421
407
private getItems():Promise<OrderListItem[]> {
422
408
returnPromise.resolve([{
@@ -437,27 +423,27 @@ export default class MockSpPnPjsExampleViewModel {
437
423
}
438
424
439
425
/**
440
-
* Adds an item to the list
426
+
* Simulates adding an item to the list
441
427
*/
442
428
public addItem():void {
443
429
444
430
if (this.newItemTitle() !==""&&this.newItemNumber() !=="") {
445
431
446
-
//add the new item to the display
432
+
//Add the new item to the display
447
433
this.items.push({
448
434
Id: this.items.length,
449
435
OrderNumber: this.newItemNumber(),
450
436
Title: this.newItemTitle(),
451
437
});
452
438
453
-
//clear the form
439
+
//Clear the form
454
440
this.newItemTitle("");
455
441
this.newItemNumber("");
456
442
}
457
443
}
458
444
459
445
/**
460
-
* Deletes an item from the list
446
+
* Simulates deleting an item from the list
461
447
*/
462
448
public deleteItem(data):void {
463
449
@@ -469,12 +455,12 @@ export default class MockSpPnPjsExampleViewModel {
469
455
```
470
456
### Update Webpart
471
457
472
-
Finally we need to update the webpart to use the mock data when appropriate, to do so start by opening the SpPnPjsExampleWebPart.ts file. Start by importing the mock ViewModel web just created.
458
+
Finally, we need to update the webpart to use the mock data when appropriate. Open the **SpPnPjsExampleWebPart.ts** file. Start by importing the mock ViewModel web just created:
Finally type gulp serve in the console to bring up the local workbench, which now will work with the mock data. (If you already have the server running stop it using Ctrl+C and then restart it)
490
+
Finally, type `gulp serve` in the console to bring up the local workbench, which now will work with the mock data. (If you already have the server running, stop it using Ctrl+C and then restart it):
505
491
506
492
```sh
507
493
gulp serve
@@ -516,4 +502,4 @@ Remember you can find the full sample [here](https://github.com/SharePoint/sp-de
516
502
517
503
## Provide Feedback / Report Issues
518
504
519
-
If you have any feedback or need to report as issue with sp-pnp-js please use the [issues list](https://github.com/SharePoint/PnP-JS-Core/issues) in that repo.
505
+
If you have any feedback or need to report an issue with sp-pnp-js, please use the [issues list](https://github.com/SharePoint/PnP-JS-Core/issues) in that repo.
0 commit comments