程式碼片段 (Snippet) 指南

contributes.snippets 貢獻點允許您將程式碼片段(snippets)封裝到 Visual Studio Code 擴充功能中以進行分享。

建立程式碼片段主題包含了建立程式碼片段的所有資訊。本指南/範例僅展示如何將您自己的程式碼片段轉換為擴充功能以供分享。建議的工作流程如下:

  • 使用 Snippets: Configure User Snippets (程式碼片段:設定使用者程式碼片段) 指令建立並測試您的程式碼片段
  • 當您對程式碼片段感到滿意後,將整個 JSON 檔案複製到擴充功能資料夾中,例如命名為 snippets.json
  • 將下列程式碼片段貢獻加入您的 package.json
{
  "contributes": {
    "snippets": [
      {
        "language": "javascript",
        "path": "./snippets.json"
      }
    ]
  }
}

提示:在您的 package.json 中使用下列設定,將您的擴充功能標記為程式碼片段擴充功能

{
  "categories": ["Snippets"]
}

您可以在此找到完整的原始程式碼:https://github.com/microsoft/vscode-extension-samples/tree/main/snippet-sample

使用 TextMate 程式碼片段

您也可以使用 yo code 擴充功能產生器,將 TextMate 程式碼片段 (.tmSnippets) 加入到您的 VS Code 安裝中。該產生器提供一個 New Code Snippets 選項,可讓您指定包含多個 .tmSnippets 檔案的資料夾,這些檔案將被封裝成 VS Code 程式碼片段擴充功能。該產生器也支援 Sublime 程式碼片段 (.sublime-snippets)。

最終的產生器輸出包含兩個檔案:一個是用於將程式碼片段整合至 VS Code 的中繼資料擴充功能資訊清單 package.json,以及一個包含已轉換為 VS Code 格式程式碼片段的 snippets.json 檔案。

.
├── snippets                    // VS Code integration
│   └── snippets.json           // The JSON file w/ the snippets
└── package.json                // extension's manifest

將產生的程式碼片段資料夾複製到您 .vscode/extensions 資料夾下的新資料夾中,並重新啟動 VS Code。

© . This site is unofficial and not affiliated with Microsoft.