### Install @pnp/sp-admin
Source: https://pnp.github.io/pnpjs/sp-admin
Install the package using npm.
```bash
npm install @pnp/sp-admin --save
```
--------------------------------
### Start Development Server
Source: https://pnp.github.io/pnpjs/contributing/npm-scripts
Executes the serve command to start the development environment.
```bash
npm start
```
--------------------------------
### Install @pnp/msaljsclient and @azure/msal-browser
Source: https://pnp.github.io/pnpjs/msaljsclient
Commands to install the required packages for MSAL authentication.
```bash
npm install @pnp/msaljsclient --save
```
```bash
npm install @azure/msal-browser --save-dev
```
--------------------------------
### Install @pnp/azidjsclient
Source: https://pnp.github.io/pnpjs/azidjsclient
Command to install the required package via npm.
```bash
npm install @pnp/azidjsclient --save
```
--------------------------------
### Install Project Dependencies
Source: https://pnp.github.io/pnpjs/contributing/setup-dev-machine
Run this command in the root of the cloned repository to install all necessary project dependencies.
```bash
npm install
```
--------------------------------
### Install MkDocs Material Theme
Source: https://pnp.github.io/pnpjs/contributing/documentation
Installs the MkDocs Material theme, which is used for styling the documentation. Ensure Python and pip are installed and added to your PATH.
```bash
python -m pip install mkdocs-material
```
--------------------------------
### Install PnPjs Packages
Source: https://pnp.github.io/pnpjs/getting-started
Command to install the core SharePoint and Graph API packages.
```bash
npm install @pnp/sp @pnp/graph --save
```
--------------------------------
### Get Installed Apps for Current User
Source: https://pnp.github.io/pnpjs/graph/teams
Retrieves a list of applications installed for the currently authenticated user.
```typescript
import { graphfi } from "@pnp/graph";
import "@pnp/graph/teams";
const graph = graphfi(...);
const installedApps = await graph.me.installedApps();
```
--------------------------------
### Typed Request Examples
Source: https://pnp.github.io/pnpjs/concepts/typings
Examples demonstrating how to type specific properties when fetching fields or lists.
```typescript
const _sp = spfi().using(SPFx(this.context));
//Typing the Title property of a field
const field = await _sp.site.rootWeb.fields.getById(titleFieldId).select("Title")<{ Title: string }>();
//Typing the ParentWebUrl property of the selected list.
const testList = await _sp.web.lists.getByTitle('MyList').select("ParentWebUrl")<{ ParentWebUrl: string }>();
```
--------------------------------
### Install MSAL client package
Source: https://pnp.github.io/pnpjs/concepts/auth-spfx
Command to install the required MSAL client package for PnPjs.
```bash
npm install @pnp/msaljsclient --save
```
--------------------------------
### Install SP Nightly Build
Source: https://pnp.github.io/pnpjs/concepts/nightly-builds
Use this command to install the nightly build for the SP package. Nightly builds are not as deeply tested as monthly releases.
```bash
npm install @pnp/sp@v3nightly --save
```
--------------------------------
### Install MkDocs Redirect Plugin
Source: https://pnp.github.io/pnpjs/contributing/documentation
Installs the mkdocs-redirects plugin, which is used to handle redirects from moved documentation pages. This helps maintain SEO and user experience.
```bash
pip install mkdocs-redirects
```
--------------------------------
### Usage Example for AsyncPager
Source: https://pnp.github.io/pnpjs/concepts/async-paging
Instantiate and use the `AsyncPager` class to navigate through pages of items from a SharePoint list. This example demonstrates fetching the first page of items.
```typescript
const pager = new AsyncPager(sp.web.lists.getByTitle("BigList").items.top(1000));
const items1 = await pager.next();
```
--------------------------------
### Install SharePoint NodeJS dependencies
Source: https://pnp.github.io/pnpjs/getting-started
Install the required packages for SharePoint integration in NodeJS.
```cmd
npm i @pnp/sp @pnp/nodejs
```
--------------------------------
### Install Graph NodeJS dependencies
Source: https://pnp.github.io/pnpjs/getting-started
Install the required packages for Microsoft Graph integration in NodeJS.
```cmd
npm i @pnp/graph @pnp/nodejs
```
--------------------------------
### Setup Supporting Code for Related Items API
Source: https://pnp.github.io/pnpjs/sp/related-items
This code block provides the necessary setup for using the related items API. It ensures the required modules are imported and sets up two task lists for demonstrating related item operations.
```typescript
import { spfi, SPFx, extractWebUrl } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/related-items/web";
import "@pnp/sp/lists/web";
import "@pnp/sp/items/list";
import "@pnp/sp/files/list";
import { IList } from "@pnp/sp/lists";
import { getRandomString } from "@pnp/core";
const sp = spfi(...);
// setup some lists (or just use existing ones this is just to show the complete process)
// we need two lists to use for creating related items, they need to use template 107 (task list)
const ler1 = await sp.web.lists.ensure("RelatedItemsSourceList", "", 107);
const ler2 = await sp.web.lists.ensure("RelatedItemsTargetList", "", 107);
const sourceList = ler1.list;
const targetList = ler2.list;
const sourceListName = await sourceList.select("Id")().then(r => r.Id);
const targetListName = await targetList.select("Id")().then(r => r.Id);
// or whatever you need to get the web url, both our example lists are in the same web.
const webUrl = sp.web.toUrl();
// ...individual samples start here
```
--------------------------------
### Get an Installed App for Current User
Source: https://pnp.github.io/pnpjs/graph/teams
Retrieves details of a specific application installed for the currently authenticated user by its ID.
```typescript
import { graphfi } from "@pnp/graph";
import "@pnp/graph/users";
import "@pnp/graph/teams";
const graph = graphfi(...);
const addedApp = await graph.me.installedApps.getById('NWI2NDk4MzQtNzQxMi00Y2NlLTllNjktMTc2ZTk1YTM5NGY1IyNhNmI2MzM2NS0zMWE0LTRmNDMtOTJlYy03MTBiNzE1NTdhZjk')();
```
--------------------------------
### Get Installed Apps for a Specific User
Source: https://pnp.github.io/pnpjs/graph/teams
Retrieves a list of applications installed for a specific user, identified by their email address.
```typescript
import { graphfi } from "@pnp/graph";
import "@pnp/graph/teams";
const graph = graphfi(...);
const installedAppsForUsers = await graph.users('user@contoso.com').installedApps();
```
--------------------------------
### Get Installed Apps for a Team
Source: https://pnp.github.io/pnpjs/graph/teams
Retrieves a list of applications installed in a specific Microsoft Team. Requires the Team ID.
```typescript
import { graphfi } from "@pnp/graph";
import "@pnp/graph/teams";
const graph = graphfi(...);
const installedApps = await graph.teams.getById('3531f3fb-f9ee-4f43-982a-6c90d8226528').installedApps();
```
--------------------------------
### GET /web/regionalSettings/installedLanguages
Source: https://pnp.github.io/pnpjs/sp/regional-settings
Retrieves a list of languages installed on the web.
```APIDOC
## GET /web/regionalSettings/installedLanguages
### Description
Returns a list of the installed languages in the web.
### Method
GET
### Endpoint
/web/regionalSettings/getInstalledLanguages()
### Request Example
const s = await sp.web.regionalSettings.getInstalledLanguages();
```
--------------------------------
### Get SharePoint List by ID
Source: https://pnp.github.io/pnpjs/sp/lists
Retrieves a list using its GUID. The ID parameter is case-insensitive and accepts GUIDs with or without curly braces.
```typescript
import { spfi } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
const sp = spfi(...);
// get the list by Id
const list = sp.web.lists.getById("03b05ff4-d95d-45ed-841d-3855f77a2483");
// we can use this 'list' variable to execute more queries on the list:
const r = await list.select("Title")();
// show the response from the server
console.log(r.Title);
```
--------------------------------
### Serve MkDocs Documentation Locally
Source: https://pnp.github.io/pnpjs/contributing/documentation
Serves the MkDocs documentation locally, allowing you to preview changes before deploying. Open a browser to the specified address to view the documentation.
```bash
mkdocs serve
```
--------------------------------
### Initialize SPFx and Graph Behaviors
Source: https://pnp.github.io/pnpjs/sp/behaviors
Demonstrates setting up both SP and Graph libraries with their respective SPFx behaviors using the same SPFx context.
```typescript
import { GraphFI, graphfi, SPFx as graphSPFx } from '@pnp/graph'
import { SPFI, spfi, SPFx as spSPFx } from '@pnp/sp'
const sp = spfi().using(spSPFx(this.context));
const graph = graphfi().using(graphSPFx(this.context));
```
--------------------------------
### Get SharePoint list form by Id
Source: https://pnp.github.io/pnpjs/sp/forms
Retrieves a specific form from a list by its GUID. The library accepts GUIDs with or without curly braces and is case-insensitive.
```typescript
import { spfi } from "@pnp/sp";
import "@pnp/sp/forms";
import "@pnp/sp/lists";
const sp = spfi(...);
// get the field by Id for web
const form = sp.web.lists.getByTitle("Documents").forms.getById("{c4486774-f1e2-4804-96f3-91edf3e22a19}")();
```
--------------------------------
### Initialize with DefaultInit
Source: https://pnp.github.io/pnpjs/graph/behaviors
Uses DefaultInit to include Telemetry, RejectOnError, and ResolveOnData behaviors.
```typescript
import { graphfi, DefaultInit } from "@pnp/graph";
import "@pnp/graph/users";
const graph = graphfi().using(DefaultInit());
await graph.users();
```
--------------------------------
### GET /features/getById
Source: https://pnp.github.io/pnpjs/sp/features
Retrieves information about a specific feature using its GUID.
```APIDOC
## GET /features/getById
### Description
Gets the information about a feature for the given GUID at the Site or Web level.
### Parameters
#### Path Parameters
- **id** (string) - Required - The GUID of the feature to retrieve.
### Request Example
const webFeature = await sp.web.features.getById("a7a2793e-67cd-4dc1-9fd0-43f61581207a")();
```
--------------------------------
### Get an App
Source: https://pnp.github.io/pnpjs/sp/alm
Retrieves details for a specific app using its GUID.
```typescript
const app = await catalog.getAppById("5137dff1-0b79-4ebc-8af4-ca01f7bd393c")();
```
--------------------------------
### Queryable Constructor Examples
Source: https://pnp.github.io/pnpjs/queryable/queryable
Demonstrates various ways to construct Queryable instances, inheriting observers or creating new ones, and setting absolute or relative URLs.
```typescript
// represents a fully configured queryable with url and registered observers
// url: https://something.com
const baseQueryable;
// child1 will:
// - reference the observers of baseQueryable
// - have a url of "https://something.com/subpath"
const child1 = Child(baseQueryable, "subpath");
// child2 will:
// - reference the observers of baseQueryable
// - have a url of "https://something.com"
const child2 = Child(baseQueryable);
// nonchild1 will:
// - have NO registered observers or connection to baseQueryable
// - have a url of "https://somethingelse.com"
const nonchild1 = Child("https://somethingelse.com");
// nonchild2 will:
// - have NO registered observers or connection to baseQueryable
// - have a url of "https://somethingelse.com/subpath"
const nonchild2 = Child("https://somethingelse.com", "subpath");
// rebased1 will:
// - reference the observers of baseQueryable
// - have a url of "https://somethingelse.com"
const rebased1 = Child([baseQueryable, "https://somethingelse.com"]);
// rebased2 will:
// - reference the observers of baseQueryable
// - have a url of "https://somethingelse.com/subpath"
const rebased2 = Child([baseQueryable, "https://somethingelse.com"], "subpath");
```
--------------------------------
### Initialize PnPClientStorage
Source: https://pnp.github.io/pnpjs/core/storage
Basic setup to access local storage using the PnPClientStorage class.
```typescript
import { PnPClientStorage } from "@pnp/core";
const storage = new PnPClientStorage();
const myvalue = storage.local.get("mykey");
```
--------------------------------
### Get Field by Id
Source: https://pnp.github.io/pnpjs/sp/fields
Retrieves a field from a web or list collection using its GUID. The ID parameter is case-insensitive and accepts GUIDs with or without curly braces.
```typescript
import { spfi } from "@pnp/sp";
import { IField, IFieldInfo } from "@pnp/sp/fields/types";
import "@pnp/sp/webs";
import "@pnp/sp/lists/web";
import "@pnp/sp/fields";
// set up sp root object
const sp = spfi(...);
// get the field by Id for web
const field: IField = sp.web.fields.getById("03b05ff4-d95d-45ed-841d-3855f77a2483");
// get the field by Id for list 'My List'
const field2: IFieldInfo = await sp.web.lists.getByTitle("My List").fields.getById("03b05ff4-d95d-45ed-841d-3855f77a2483")();
// we can use this 'field' variable to execute more queries on the field:
const r = await field.select("Title")();
// show the response from the server
console.log(r.Title);
```
--------------------------------
### Serve Bundled Script
Source: https://pnp.github.io/pnpjs/contributing/npm-scripts
Starts a debugging server using ./debug/serve/main.ts as the entry point for browser-based debugging.
```bash
npm run serve
```
--------------------------------
### Get People Followed By Specific User
Source: https://pnp.github.io/pnpjs/sp/profiles
Retrieves a list of users that a specified user is following. Note: The example code provided appears to be a duplicate of 'Get followers for a specific user'. Ensure the correct method is called.
```typescript
const sp = spfi(...);
const loginName = "i:0#.f|membership|testuser@mytenant.onmicrosoft.com";
const folowers = await sp.profiles.getFollowersFor(loginName);
followers.forEach((value) => {
...
});
```
--------------------------------
### Get feature details by ID
Source: https://pnp.github.io/pnpjs/sp/features
Retrieves information about a specific feature using its GUID at either the web or site level.
```typescript
import { spfi } from "@pnp/sp";
const sp = spfi(...);
//Example of GUID format a7a2793e-67cd-4dc1-9fd0-43f61581207a
const webFeatureId = "guid-of-web-feature";
const webFeature = await sp.web.features.getById(webFeatureId)();
const siteFeatureId = "guid-of-site-scope-feature";
const siteFeature = await sp.site.features.getById(siteFeatureId)();
```
--------------------------------
### Configure SPFI and GraphFI with Azure Identity
Source: https://pnp.github.io/pnpjs/azidjsclient
Example showing how to initialize SPFI and GraphFI objects using the AzureIdentity behavior.
```typescript
import { DefaultAzureCredential } from "@azure/identity";
import { spfi } from "@pnp/sp";
import { graphfi } from "@pnp/sp";
import { SPDefault, GraphDefault } from "@pnp/nodejs";
import { AzureIdentity } from "@pnp/azidjsclient";
import "@pnp/sp/webs";
import "@pnp/graph/me";
const credential = new DefaultAzureCredential();
const sp = spfi("https://tenant.sharepoint.com/sites/dev").using(
SPDefault(),
AzureIdentity(credential, [`https://${tenant}.sharepoint.com/.default`], null)
);
const graph = graphfi().using(
GraphDefault(),
AzureIdentity(credential, ["https://graph.microsoft.com/.default"], null)
);
const webData = await sp.web();
const meData = await graph.me();
```
--------------------------------
### Get Field by Id
Source: https://pnp.github.io/pnpjs/sp/fields
Retrieves a field from a web or list collection using its unique ID. Supports GUIDs with or without curly braces and is case-insensitive.
```APIDOC
## GET /web/fields Get Field by Id
### Description
Gets a field from the collection by id (guid). The Id parameter is also case insensitive.
### Method
GET
### Endpoint
`/web/fields` or `/web/lists/getByTitle("List Title")/fields`
### Parameters
#### Path Parameters
- **Id** (string) - Required - The GUID of the field to retrieve.
### Request Example
```javascript
import { spfi } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists/web";
import "@pnp/sp/fields";
const sp = spfi("YOUR_SHAREPOINT_URL");
// Get field by Id for the web
const field = await sp.web.fields.getById("03b05ff4-d95d-45ed-841d-3855f77a2483");
// Get field by Id for a specific list
const listField = await sp.web.lists.getByTitle("My List").fields.getById("03b05ff4-d95d-45ed-841d-3855f77a2483");
// Select specific properties
const fieldTitle = await field.select("Title")();
console.log(fieldTitle.Title);
```
### Response
#### Success Response (200)
- **IFieldInfo** (object) - Contains information about the retrieved field.
#### Response Example
```json
{
"Title": "My Field Title",
"Id": "03b05ff4-d95d-45ed-841d-3855f77a2483",
"InternalName": "MyField",
"TypeAsString": "Text"
}
```
```
--------------------------------
### Initialize with DefaultInit Behavior
Source: https://pnp.github.io/pnpjs/sp/behaviors
Use DefaultInit to include Telemetry, RejectOnError, and ResolveOnData. It also configures cache and credentials for RequestInit.
```typescript
import { spfi, DefaultInit } from "@pnp/sp";
import "@pnp/sp/webs";
const sp = spfi().using(DefaultInit());
await sp.web();
```
--------------------------------
### Get Hub Site by Id
Source: https://pnp.github.io/pnpjs/sp/hubsites
Retrieves a specific hub site by its unique ID (GUID). The `Title` property of the hub site is logged to the console.
```typescript
import { spfi } from "@pnp/sp";
import { IHubSiteInfo } from "@pnp/sp/hubsites";
import "@pnp/sp/hubsites";
const sp = spfi(...);
const hubsite: IHubSiteInfo = await sp.hubSites.getById("3504348e-b2be-49fb-a2a9-2d748db64beb")();
// log hub site title to console
console.log(hubsite.Title);
```
--------------------------------
### Get List Changes
Source: https://pnp.github.io/pnpjs/sp/lists
Retrieves a collection of changes that have occurred within a list based on a specified query. This example queries for Add, DeleteObject, and Rename changes.
```typescript
import { IChangeQuery } from "@pnp/sp";
// build the changeQuery object, here we look att changes regarding Add, DeleteObject and Restore
const changeQuery: IChangeQuery = {
Add: true,
ChangeTokenEnd: null,
ChangeTokenStart: null,
DeleteObject: true,
Rename: true,
Restore: true,
};
// get list changes
const r = await list.getChanges(changeQuery);
// log changes to console
console.log(r);
```
--------------------------------
### Import and Use PnPjs
Source: https://pnp.github.io/pnpjs/getting-started
Basic example of importing a utility function and executing it.
```ts
import { getRandomString } from "@pnp/core";
(function() {
// get and log a random string
console.log(getRandomString(20));
})()
```
--------------------------------
### Get Channel by ID
Source: https://pnp.github.io/pnpjs/graph/teams
Retrieves a specific channel within a team using both the team ID and the channel ID. The channel ID is typically a GUID followed by a thread identifier.
```typescript
import { graphfi } from "@pnp/graph";
import "@pnp/graph/teams";
const graph = graphfi(...);
const channel = await graph.teams.getById('3531f3fb-f9ee-4f43-982a-6c90d8226528').channels.getById('19:65723d632b384ca89c81115c281428a3@thread.skype')();
```
--------------------------------
### Implement init lifecycle moment
Source: https://pnp.github.io/pnpjs/queryable/queryable
The init moment allows for synchronous setup tasks before the lifecycle begins. It is not await-aware.
```typescript
query.on.init(function (this: Queryable) {
// init is a great place to register additioanl observers ahead of the lifecycle
this.on.pre(async function (this: Quyerable, url, init, result) {
// stuff happens
return [url, init, result];
});
});
```
--------------------------------
### Get List Items by CAML Query
Source: https://pnp.github.io/pnpjs/sp/lists
Fetches list items from SharePoint using a CAML query. This example retrieves the 'Title' field and limits results to 5 rows.
```typescript
import { ICamlQuery } from "@pnp/sp/lists";
// build the caml query object (in this example, we include Title field and limit rows to 5)
const caml: ICamlQuery = {
ViewXml: "5",
};
// get list items
const r = await list.getItemsByCAMLQuery(caml);
// log resulting array to console
console.log(r);
```
--------------------------------
### Get List Changes with Time Range
Source: https://pnp.github.io/pnpjs/sp/lists
Retrieves list changes within a specific time range using ChangeTokenStart. This example filters for Add and Update changes on Items.
```typescript
import { IChangeQuery, createChangeToken } from "@pnp/sp";
//Resource is the list Id (as Guid)
const changeTokenStart = createChangeToken("list", list.Id, new Date("2022-02-22"));
// build the changeQuery object, here we look at changes regarding Add and Update for Items.
const changeQuery: IChangeQuery = {
Add: true,
Update: true,
Item: true,
ChangeTokenEnd: null,
ChangeTokenStart: changeTokenStart,
};
// get list changes
const r = await list.getChanges(changeQuery);
// log changes to console
console.log(r);
```
--------------------------------
### Get List Items with Expanded Lookup Field by CAML Query
Source: https://pnp.github.io/pnpjs/sp/lists
Fetches list items using a CAML query and expands a specified lookup field. This example expands the 'RoleAssignments' field.
```typescript
import { ICamlQuery } from "@pnp/sp/lists";
// build the caml query object (in this example, we include Title field and limit rows to 5)
const caml: ICamlQuery = {
ViewXml: "5",
};
// get list items
const r = await list.getItemsByCAMLQuery(caml, "RoleAssignments");
// log resulting item array to console
console.log(r);
```
--------------------------------
### Write a Mocha test for PnPjs items
Source: https://pnp.github.io/pnpjs/contributing/debug-tests
Demonstrates setting up a test suite with Mocha and Chai, including list initialization and batch item creation.
```typescript
import { getRandomString } from "@pnp/core";
import { testSettings } from "../main";
import { expect } from "chai";
import { sp } from "@pnp/sp";
import "@pnp/sp/lists/web";
import "@pnp/sp/items/list";
import { IList } from "@pnp/sp/lists";
describe("Items", () => {
// any tests that make a web request should be withing a block checking if web tests are enabled
if (testSettings.enableWebTests) {
// a block scoped var we will use across our tests
let list: IList = null;
// we use the before block to setup
// executed before all the tests in this block, see the mocha docs for more details
// mocha prefers using function vs arrow functions and this is recommended
before(async function () {
// execute a request to ensure we have a list
const ler = await sp.web.lists.ensure("ItemTestList", "Used to test item operations");
list = ler.list;
// in this case we want to have some items in the list for testing so we add those
// only if the list was just created
if (ler.created) {
// add a few items to get started
const batch = sp.web.createBatch();
list.items.inBatch(batch).add({ Title: `Item ${getRandomString(4)}` });
list.items.inBatch(batch).add({ Title: `Item ${getRandomString(4)}` });
list.items.inBatch(batch).add({ Title: `Item ${getRandomString(4)}` });
list.items.inBatch(batch).add({ Title: `Item ${getRandomString(4)}` });
list.items.inBatch(batch).add({ Title: `Item ${getRandomString(4)}` });
await batch.execute();
}
});
// this test has a label "get items" and is run via an async function
it("get items", async function () {
// make a request for the list's items
const items = await list.items();
// report that we expect that result to be an array with more than 0 items
expect(items.length).to.be.gt(0);
});
// ... remainder of code removed
}
}
```
--------------------------------
### Get Site Map Menu State
Source: https://pnp.github.io/pnpjs/sp/navigation
Retrieves the menu state of a SiteMapProvider. Can specify a starting node key and depth, or a custom provider name. Use when needing to inspect the site map structure.
```typescript
import { spfi } from "@pnp/sp";
import "@pnp/sp/navigation";
const sp = spfi(...);
// Will return a menu state of the default SiteMapProvider 'SPSiteMapProvider' where the dump starts a the RootNode (within the site) with a depth of 10 levels.
const state = await sp.navigation.getMenuState();
// Will return the menu state of the 'SPSiteMapProvider', starting with the node with the key '1002' with a depth of 5
const state2 = await sp.navigation.getMenuState("1002", 5);
// Will return the menu state of the 'CurrentNavSiteMapProviderNoEncode' from the root node of the provider with a depth of 5
const state3 = await sp.navigation.getMenuState(null, 5, "CurrentNavSiteMapProviderNoEncode");
```
--------------------------------
### Configure settings.js for Local Development
Source: https://pnp.github.io/pnpjs/contributing/settings
Define the MSAL initialization and testing environment settings required for PnPjs library debugging.
```javascript
const privateKey = `-----BEGIN RSA PRIVATE KEY-----
your private key, read from a file or included here
-----END RSA PRIVATE KEY-----
`;
var msalInit = {
auth: {
authority: "https://login.microsoftonline.com/{tenant id}",
clientCertificate: {
thumbprint: "{certificate thumbnail}",
privateKey: privateKey,
},
clientId: "{AAD App registration id}",
}
}
export const settings = {
testing: {
enableWebTests: true,
testUser: "i:0#.f|membership|user@consto.com",
testGroupId:"{ Microsoft 365 Group ID }",
sp: {
url: "{required for MSAL - absolute url of test site}",
notificationUrl: "{ optional: notification url }",
msal: {
init: msalInit,
scopes: ["https://{tenant}.sharepoint.com/.default"]
},
},
graph: {
msal: {
init: msalInit,
scopes: ["https://graph.microsoft.com/.default"]
},
},
},
}
```
--------------------------------
### Retrieve Site Scripts
Source: https://pnp.github.io/pnpjs/sp/site-scripts
Retrieve all site scripts or a single site script by its ID. The first example shows how to get a count and the title of the first script, while the second retrieves metadata for a specific script.
```typescript
import { spfi } from "@pnp/sp";
import "@pnp/sp/site-scripts";
const sp = spfi(...);
// Retrieving all site scripts
const allSiteScripts = await sp.siteScripts.getSiteScripts();
console.log(allSiteScripts.length > 0 ? allSiteScripts[0].Title : "");
// Retrieving a single site script by Id
const siteScript = await sp.siteScripts.getSiteScriptMetadata("884ed56b-1aab-4653-95cf-4be0bfa5ef0a");
console.log(siteScript.Title);
```
--------------------------------
### Access Web with 'all' Preset
Source: https://pnp.github.io/pnpjs/sp/webs
Utilize the 'all' preset for accessing the web instance. This imports all available PnPjs features.
```typescript
import { spfi } from "@pnp/sp";
import "@pnp/sp/presets/all";
const sp = spfi(...);
const r = await sp.web();
```
--------------------------------
### GET /getFolderById
Source: https://pnp.github.io/pnpjs/sp/folders
You can get a folder by its UniqueId from a web.
```APIDOC
## GET /getFolderById
### Description
Retrieves a folder object using its UniqueId.
### Method
GET
### Endpoint
/web/getFolderById("folderUniqueId")
### Parameters
#### Path Parameters
- **folderUniqueId** (string) - Required - The UniqueId of the folder.
### Response
#### Success Response (200)
- **folder** (object) - An object representing the folder.
### Response Example
```json
{
"Name": "My Folder",
"ServerRelativeUrl": "/sites/YourSite/My List/My Folder"
}
```
```
--------------------------------
### Console output example
Source: https://pnp.github.io/pnpjs/logging
The resulting console output format when using a prefix.
```text
MyAwesomeWebPart - My special message
```
--------------------------------
### GET /properties
Source: https://pnp.github.io/pnpjs/sp/folders
Gets this folder's properties.
```APIDOC
## GET /properties
### Description
Gets this folder's properties.
### Method
GET
### Endpoint
/web/getFolderByServerRelativePath("folderPath")/properties
### Parameters
#### Path Parameters
- **folderPath** (string) - Required - The server-relative path to the folder.
### Response
#### Success Response (200)
- **properties** (object) - An object containing the folder's properties.
### Response Example
```json
{
"Name": "Folder2",
"TimeCreated": "2023-10-27T10:00:00Z",
"TimeLastModified": "2023-10-27T10:00:00Z"
}
```
```
--------------------------------
### Package Project
Source: https://pnp.github.io/pnpjs/contributing/npm-scripts
Creates package directories under the dist folder to preview npm package contents.
```bash
npm run package
```
--------------------------------
### GET /parentFolder
Source: https://pnp.github.io/pnpjs/sp/folders
Gets the parent folder, if available.
```APIDOC
## GET /parentFolder
### Description
Gets the parent folder, if available.
### Method
GET
### Endpoint
/web/getFolderByServerRelativePath("folderPath")/parentFolder
### Parameters
#### Path Parameters
- **folderPath** (string) - Required - The server-relative path to the folder.
### Response
#### Success Response (200)
- **parentFolder** (object) - An object representing the parent folder.
### Response Example
```json
{
"Name": "Shared Documents",
"ServerRelativeUrl": "/sites/YourSite/Shared Documents"
}
```
```
--------------------------------
### Connect to a Different Web using PnP JS
Source: https://pnp.github.io/pnpjs/getting-started
Demonstrates various methods to create a connection to a different SharePoint web. Options include creating a new Queryable instance, assigning from an existing web's configuration, or copying an existing SPQuerable instance to point to a new web URL.
```typescript
import { spfi, SPFx } from "@pnp/sp";
import { AssignFrom } from "@pnp/core";
import "@pnp/sp/webs";
//Connection to the current context's Web
const sp = spfi(...);
// Option 1: Create a new instance of Queryable
const spWebB = spfi({Other Web URL}).using(SPFx(this.context));
// Option 2: Copy/Assign a new instance of Queryable using the existing
const spWebB = spfi({Other Web URL}).using(AssignFrom(sp.web));
// Option 3: Create a new instance of Queryable using other credentials?
const spWebB = spfi({Other Web URL}).using(SPFx(this.context));
// Option 4: Create new Web instance by using copying SPQuerable and new pointing to new web url (e.g. https://contoso.sharepoint.com/sites/Web2)
const web = Web([sp.web, {Other Web URL}]);
```
--------------------------------
### GET /files
Source: https://pnp.github.io/pnpjs/sp/folders
Gets all files inside a folder.
```APIDOC
## GET /files
### Description
Gets all files inside a folder.
### Method
GET
### Endpoint
/web/getFolderByServerRelativePath("folderPath")/files
### Parameters
#### Path Parameters
- **folderPath** (string) - Required - The server-relative path to the folder.
### Response
#### Success Response (200)
- **files** (array) - An array of file objects.
### Response Example
```json
[
{
"Name": "example.docx",
"ServerRelativeUrl": "/sites/YourSite/Shared Documents/example.docx"
}
]
```
```
--------------------------------
### Create a Notebook
Source: https://pnp.github.io/pnpjs/graph/onenote
Creates a new notebook for the user.
```typescript
import { graphfi } from "@pnp/graph";
import "@pnp/graph/users";
import "@pnp/graph/onenote";
const graph = graphfi(...);
const userNotebookAdd = await graph.me.onenote.notebooks.add("New Notebook");
```
--------------------------------
### Get folder by UniqueId
Source: https://pnp.github.io/pnpjs/sp/folders
Retrieves a folder object using its UniqueId. This involves first getting the UniqueId from a list item and then using it to get the folder.
```typescript
import { spfi } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/folders";
import { IFolder } from "@pnp/sp/folders";
const sp = spfi(...);
const folderItem = sp.web.lists.getByTitle("My List").items.getById(1).select("UniqueId")()
const folder: IFolder = sp.web.getFolderById(folderItem.UniqueId);
```
--------------------------------
### Generate a GUID with getGUID
Source: https://pnp.github.io/pnpjs/core/util
Creates a random GUID string.
```typescript
import { getGUID } from "@pnp/core";
const newGUID = getGUID();
```
--------------------------------
### Build Project
Source: https://pnp.github.io/pnpjs/contributing/npm-scripts
Transpiles TypeScript into JavaScript using the pnpbuild CLI.
```bash
npm run build
```
--------------------------------
### Sharing API - Import All
Source: https://pnp.github.io/pnpjs/sp/sharing
Demonstrates how to import and attach all sharing methods to sharable types (Item, File, Folder, Web) by including the entire sharing sub-module.
```APIDOC
## Import All Sharing Methods
### Description
Import and attach the sharing methods to all four sharable types (Item, File, Folder, Web) by including all of the sharing sub-module.
### Code Example
```typescript
import "@pnp/sp/sharing";
import "@pnp/sp/webs";
import "@pnp/sp/site-users/web";
import { spfi } from "@pnp/sp";
const sp = spfi("YOUR_SHAREPOINT_URL");
// Example usage: Get a user and then share with them
const user = await sp.web.siteUsers.getByEmail("user@example.com")();
const r = await sp.web.shareWith(user.LoginName);
```
```
--------------------------------
### GET /web/defaultDocumentLibrary
Source: https://pnp.github.io/pnpjs/sp/webs
Gets a reference to the default document library of a web.
```APIDOC
## GET /web/defaultDocumentLibrary
### Description
Get a reference to the default document library of a web.
### Method
GET
### Endpoint
/web/defaultDocumentLibrary
```
--------------------------------
### Configure and Initialize MSAL Authentication
Source: https://pnp.github.io/pnpjs/msaljsclient
Setup MSAL options, initialize the SP client, and perform logout operations.
```typescript
import type { MSALOptions } from "@pnp/msaljsclient";
import { spfi, SPBrowser } from "@pnp/sp";
import { MSAL, getMSAL } from "@pnp/msaljsclient";
import "@pnp/sp/webs";
import "@pnp/sp/site-users/web";
const options: MSALOptions = {
configuration: {
auth: {
authority: "https://login.microsoftonline.com/{tenant_id}/",
clientId: "{client id}",
},
cache: {
claimsBasedCachingEnabled: true // in order to avoid network call to refresh a token every time claims are requested
}
},
authParams: {
forceRefresh: false,
scopes: ["https://{tenant}.sharepoint.com/.default"],
}
};
const sp = spfi("https://tenant.sharepoint.com/sites/dev").using(SPBrowser(), MSAL(options));
const user = await sp.web.currentUser();
// For logout later on
const msalInstance = getMSAL();
const currentAccount = msalInstance.getActiveAccount();
msalInstance.logoutPopup({ account: currentAccount });
```
--------------------------------
### GET /uniqueContentTypeOrder
Source: https://pnp.github.io/pnpjs/sp/folders
Gets a value that specifies the content type order.
```APIDOC
## GET /uniqueContentTypeOrder
### Description
Gets a value that specifies the content type order.
### Method
GET
### Endpoint
/web/getFolderByServerRelativePath("folderPath").select('uniqueContentTypeOrder')()
### Parameters
#### Path Parameters
- **folderPath** (string) - Required - The server-relative path to the folder.
### Response
#### Success Response (200)
- **uniqueContentTypeOrder** (string) - The content type order value.
### Response Example
```json
{
"uniqueContentTypeOrder": "1,2,3"
}
```
```
--------------------------------
### Create a wiki page
Source: https://pnp.github.io/pnpjs/sp/sp-utilities-utility
Creates a new wiki page at the specified server-relative URL with provided HTML content.
```typescript
import { spfi } from "@pnp/sp";
import "@pnp/sp/sputilities";
import { ICreateWikiPageResult } from "@pnp/sp/sputilities";
const sp = spfi(...);
let newPage : ICreateWikiPageResult = await sp.utility.createWikiPage({
ServerRelativeUrl: "/sites/dev/SitePages/mynewpage.aspx",
WikiHtmlContent: "This is my page content. It supports rich html.",
});
// newPage contains the raw data returned by the service
console.log(newPage.data);
// newPage contains a File instance you can use to further update the new page
let file = await newPage.file();
console.log(file);
```
--------------------------------
### Web Navigation - Quick Launch
Source: https://pnp.github.io/pnpjs/sp/navigation
Retrieves all items in the quick launch navigation of the current web.
```APIDOC
## GET /api/web/navigation/quicklaunch
### Description
Retrieves all items in the quick launch navigation of the current web.
### Method
GET
### Endpoint
/api/web/navigation/quicklaunch
### Response
#### Success Response (200)
- **NavigationNode[]** (array) - An array of navigation node objects.
```
--------------------------------
### Importing Security Modules
Source: https://pnp.github.io/pnpjs/sp/security
Demonstrates selective versus full module imports for optimizing bundle size.
```typescript
import "@pnp/sp/security/web";
import "@pnp/sp/security/list";
import "@pnp/sp/security/item";
```
```typescript
import "@pnp/sp/security";
```
--------------------------------
### GET /listItemAllFields
Source: https://pnp.github.io/pnpjs/sp/folders
Gets this folder's list item field values.
```APIDOC
## GET /listItemAllFields
### Description
Gets this folder's list item field values.
### Method
GET
### Endpoint
/web/getFolderByServerRelativePath("folderPath")/listItemAllFields
### Parameters
#### Path Parameters
- **folderPath** (string) - Required - The server-relative path to the folder.
### Response
#### Success Response (200)
- **fields** (object) - An object containing the folder's list item field values.
### Response Example
```json
{
"Id": 1,
"Title": "My Folder",
"FileLeafRef": "My Folder"
}
```
```
--------------------------------
### GET /me/todo/lists/{id}
Source: https://pnp.github.io/pnpjs/graph/to-do
Get a specific task list by its unique identifier.
```APIDOC
## GET /me/todo/lists/{id}
### Description
Get a task list by id.
### Method
GET
### Endpoint
/me/todo/lists/{id}
### Parameters
#### Path Parameters
- **id** (string) - Required - The unique identifier of the task list
```
--------------------------------
### Get Top and Quick Launch Navigation
Source: https://pnp.github.io/pnpjs/sp/navigation
Retrieves all items from the top navigation bar or the quick launch menu. Ensure '@pnp/sp/webs' and '@pnp/sp/navigation' are imported.
```typescript
import { spfi } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/navigation";
const sp = spfi(...);
const top = await sp.web.navigation.topNavigationBar();
const quick = await sp.web.navigation.quicklaunch();
```
--------------------------------
### Get Excel Ranges
Source: https://pnp.github.io/pnpjs/graph/workbooks
Demonstrates how to get specific ranges using A1 coordinates or the entire used range of a worksheet. Also shows how to get the range of a named object like a table.
```typescript
// Create a range using Excel A1 coordinates
const sheet = workbook.worksheets.getByID("Sheet1");
const range = sheet.getRange("A1:C3");
// Get the full "used range" of the worksheet
const usedRange = sheet.getUsedRange();
const usedAddress = (await usedRange()).address // = e.g. "B2:L21"
// Named objects (like tables) have an underlying range, too
const tableRange = table.getRange();
```
--------------------------------
### Initialize PnPjs in SPFx
Source: https://pnp.github.io/pnpjs/getting-started
Use the spfi or graphfi factory interfaces within the onInit method to establish the SharePoint or Graph context.
```TypeScript
import { spfi, SPFx } from "@pnp/sp";
// ...
protected async onInit(): Promise {
await super.onInit();
const sp = spfi().using(SPFx(this.context));
}
// ...
```
```TypeScript
import { graphfi, SPFx } from "@pnp/graph";
// ...
protected async onInit(): Promise {
await super.onInit();
const graph = graphfi().using(SPFx(this.context));
}
// ...
```
```TypeScript
import { spfi, SPFx as spSPFx } from "@pnp/sp";
import { graphfi, SPFx as graphSPFx} from "@pnp/graph";
// ...
protected async onInit(): Promise {
await super.onInit();
const sp = spfi().using(spSPFx(this.context));
const graph = graphfi().using(graphSPFx(this.context));
}
// ...
```
--------------------------------
### Add an App for Current User
Source: https://pnp.github.io/pnpjs/graph/teams
Installs an application for the currently authenticated user. Requires the app's catalog URL.
```typescript
import { graphfi } from "@pnp/graph";
import "@pnp/graph/users";
import "@pnp/graph/teams";
const graph = graphfi(...);
const addedApp = await graph.me.installedApps.add('https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/12345678-9abc-def0-123456789a');
```
--------------------------------
### Get tenant app catalog
Source: https://pnp.github.io/pnpjs/sp/alm
Retrieves the tenant app catalog instance using the spfi context.
```typescript
import { spfi } from "@pnp/sp";
import "@pnp/sp/appcatalog";
import "@pnp/sp/webs";
const sp = spfi(...);
// get the current context web's app catalog
// this will be the site collection app catalog
const availableApps = await sp.tenantAppcatalog();
```
--------------------------------
### Create a PnPjs configuration file
Source: https://pnp.github.io/pnpjs/concepts/project-preset
Define a central configuration file to manage PnPjs initialization and logging behavior.
```typescript
import { WebPartContext } from "@microsoft/sp-webpart-base";
// import pnp, pnp logging system, and any other selective imports needed
import { spfi, SPFI, SPFx } from "@pnp/sp";
import { LogLevel, PnPLogging } from "@pnp/logging";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import "@pnp/sp/batching";
var _sp: SPFI = null;
export const getSP = (context?: WebPartContext): SPFI => {
if (context != null) {
//You must add the @pnp/logging package to include the PnPLogging behavior it is no longer a peer dependency
// The LogLevel set's at what level a message will be written to the console
_sp = spfi().using(SPFx(context)).using(PnPLogging(LogLevel.Warning));
}
return _sp;
};
```
--------------------------------
### Add a new SharePoint web
Source: https://pnp.github.io/pnpjs/sp/webs
Demonstrates creating a subweb with a title and URL, and accessing the resulting web object.
```typescript
import { spfi } from "@pnp/sp";
import { IWebAddResult } from "@pnp/sp/webs";
const sp = spfi(...);
const result = await sp.web.webs.add("title", "subweb1");
// show the response from the server when adding the web
console.log(result.data);
// we can immediately operate on the new web
result.web.select("Title")().then((w: IWebInfo) => {
// show our title
console.log(w.Title);
});
```
```typescript
import { spfi } from "@pnp/sp";
import { IWebAddResult } from "@pnp/sp/webs";
const sp = spfi(...);
// create a German language wiki site with title, url, description, which does not inherit permissions
sp.web.webs.add("wiki", "subweb2", "a wiki web", "WIKI#0", 1031, false).then((w: IWebAddResult) => {
// ...
});
```
--------------------------------
### Use SP 'all' Preset
Source: https://pnp.github.io/pnpjs/concepts/selective-imports
Utilize the 'all' preset for the SP library to attach all available functionality. This is convenient for testing or node development but is not recommended for client-side solutions due to bundle size implications.
```typescript
import "@pnp/sp/presets/all";
// placeholder for fully configuring the sp interface
const sp = spfi();
// sp.* will have all of the library functionality bound to it, tree shaking will not work
const lists = await sp.web.lists();
```
--------------------------------
### Retrieve Installed Languages
Source: https://pnp.github.io/pnpjs/sp/regional-settings
Fetch a list of languages installed on the web. Note that the installedLanguages property is deprecated.
```typescript
import { spfi } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/regional-settings/web";
const sp = spfi(...);
const s = await sp.web.regionalSettings.getInstalledLanguages();
```