You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用SharePoint PnP JS库创建列表时指定列表URL?

How to Specify Custom List URL When Creating a List with PnP JS (or SharePoint REST API)

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 Url parameter expects the relative path from your site collection/site—exactly the lists/SomeCustomListUrl segment you want. SharePoint will automatically combine this with your site’s base URL to form the full list address.
  • Ensure the Url value 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 TemplateType value based on your list type: use 100 for a standard custom list, 101 for a document library, 104 for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:57:46