如何使用SharePoint PnP JS库创建列表时指定列表URL?
Great question! I’ve run into this exact scenario before—while PnP JS’s out-of-the-box list creation method doesn’t directly expose a Url parameter (unlike CSOM’s ListCreationInformation or SPMeta2’s CustomUrl), you absolutely can achieve this by leveraging SharePoint’s REST API directly, even within the PnP JS ecosystem.
Using PnP JS with Direct REST API Call
The sp.web.lists.add() method in PnP JS abstracts the REST API but doesn’t include the Url property in its options. However, you can use PnP JS’s core HTTP capabilities to call the SharePoint REST API directly and specify the custom URL.
Here’s a working example in TypeScript:
import { sp } from "@pnp/sp"; async function createListWithCustomUrl() { // Define list properties, including the custom URL segment const listProps = { __metadata: { type: "SP.List" }, Title: "My Custom List", Url: "lists/SomeCustomListUrl", // This is your target URL segment TemplateType: 100, // Use 100 for a generic custom list; adjust for other types (e.g., 101 for document library) Description: "List created with a custom URL via PnP JS + REST" }; try { const createdList = await sp.web.post({ url: "/_api/web/lists", body: JSON.stringify(listProps), headers: { "Accept": "application/json;odata=nometadata", "Content-Type": "application/json;odata=verbose" } }); console.log("List created successfully. Full URL:", `${sp.web.url}/${listProps.Url}`); } catch (err) { console.error("Failed to create list:", err); } } // Call the function createListWithCustomUrl();
Key Notes:
- The
Urlparameter expects the relative path from your site collection/site—exactly thelists/SomeCustomListUrlsegment you want. SharePoint will automatically combine this with your site’s base URL to form the full list address. - Ensure the
Urlvalue is unique across your site (no existing list/library can use the same URL) and follows SharePoint’s naming rules (avoid special characters like#,%, or spaces unless encoded). - Adjust the
TemplateTypevalue based on your list type: use100for a standard custom list,101for a document library,104for a tasks list, etc.
Why PnP JS’s Default Method Doesn’t Support This
PnP JS’s sp.web.lists.add() method is designed for simplicity, and it uses the list title to auto-generate the URL (replacing spaces with hyphens, removing special characters). Since the REST API does support the Url parameter, the direct call approach is the official workaround when you need full control over the list’s URL.
内容的提问来源于stack exchange,提问作者Nikolay

