教學課程:建立項目範本

您可以使用 .NET 建立及部署範本,以產生專案、檔案和資源。 此教學課程屬於系列文章的第一部分,將引導您建立、安裝及解除安裝使用 dotnet new 命令的範本。

您可以在 .NET 範例 GitHub 存放庫 (英文) 中檢視已完成的範本。

提示

[項目] 範本不會顯示在 Visual Studio 的 [新增]> [新增項目] 對話方塊中。

在這部分的系列文章中,您將了解如何:

  • 建立項目範本的類別。
  • 建立範本設定資料夾和檔案。
  • 從檔案路徑安裝範本。
  • 測試項目範本。
  • 解除安裝項目範本。

必要條件

  • .NET SDK 7.0.100 或更新版本。

    該參考文章會說明範本的基本概念及構成方式。 此處重申了其中一些訊息。

  • 開啟終端並瀏覽至您要儲存及測試範本的資料夾。

重要

本文是針對 .NET 7 撰寫的。 不過,其也適用於 .NET 6 和舊版,但有一個差異:語法 dotnet new 不同。 listsearchinstalluninstall 子命令分別應為 --list--search--install--uninstall 選項。

例如,.NET 7 中的 dotnet new install 命令會在 .NET 6 中變成 dotnet new --install。 您可以使用 dotnet new --help 命令來查看所有選項漢子命令的清單。

建立必要的資料夾

本系列文章會使用「工作資料夾」來存放您的範本來源,並使用「測試資料夾」來測試您的範本。 工作資料夾和測試資料夾應該放在相同的父資料夾中。

首先,請建立父資料夾,名稱不重要。 然後,建立名為 workingtest 的兩個子資料夾。 在 working 資料夾中,建立名為 content 的子資料夾。

資料夾結構看起來應如下所示。

parent_folder
├───test
└───working
    └───content

建立項目範本

項目範本是特定類型的範本,其會包含一或多個檔案。 當您已經有一個專案並且想要產生另一個檔案 (例如設定檔或程式碼檔案) 時,這些類型的範本非常有用。 在此範例中,您將會建立能將擴充方法加入字串類型的類別。

在您的終端中,瀏覽至 working\content 資料夾,並建立名為 extensions 的新子資料夾。

working
└───content
    └───extensions

瀏覽至 extensions 資料夾,並建立名為 StringExtensions.cs 的新檔案。 在文字編輯器中開啟 檔案。 此類別將會提供名為 Reverse 的擴充方法,其能反轉字串的內容。 貼上下列程式碼並儲存檔案:

namespace System;

public static class StringExtensions
{
    public static string Reverse(this string value)
    {
        char[] tempArray = value.ToCharArray();
        Array.Reverse(tempArray);
        return new string(tempArray);
    }
}

現在範本的內容已完成,下一個步驟是建立範本設定。

建立範本設定

在此教學課程部分中,您的範本資料夾是位於 working\content\extensions

.NET 可辨識範本,因為其在範本資料夾根目錄下具有特殊的資料夾和設定檔。

首先,建立名為 .template.config 的新子資料夾,然後進入該資料夾。 然後,建立名為 template.json 的新檔案。 您的資料夾結構看起來應該像這樣:

working
└───content
    └───extensions
        └───.template.config
                template.json

使用您慣用的文字編輯器開啟 template.json,然後貼上下列 JSON 程式碼並儲存。

{
    "$schema": "http://json.schemastore.org/template",
    "author": "Me",
    "classifications": [ "Common", "Code" ],
    "identity": "ExampleTemplate.StringExtensions",
    "name": "Example templates: string extensions",
    "shortName": "stringext",
    "tags": {
      "language": "C#",
      "type": "item"
    },
    "symbols": {
      "ClassName":{
        "type": "parameter",
        "description": "The name of the code file and class.",
        "datatype": "text",
        "replaces": "StringExtensions",
        "fileRename": "StringExtensions",
        "defaultValue": "StringExtensions"
      }
    }
  }

此設定檔會包含您範本的所有設定。 您可以看見基本設定 (例如 nameshortName),但還有設定為 itemtags/type 值。 這會將您的範本分類為「項目」範本。 您可以建立的範本類型本身並無限制。 itemproject 值是 .NET 建議的常用名稱,以便讓使用者輕鬆篩選要搜尋的範本類型。

classifications 項目代表您執行 dotnet new 並取得範本清單時所會看見的 [標籤] 欄。 使用者也可以根據分類標籤搜尋。 請勿混淆 template.json 檔案中的 tags 屬性與 classifications 標籤清單。 它們是兩個不同的概念,只是名稱相同。 template.json 檔案的完整結構描述位於 JSON 結構描述存放區 (英文),並在 template.json 參考 (英文) 中提供說明。 如需 template.json 檔案的詳細資訊,請參閱 dotnet 範本化 Wiki \(英文\)。

此 JSON 物件的 symbols 部分是用來定義可在範本中使用的參數。 在此案例中,已定義一個參數,ClassName。 定義的參數包含下列設定:

  • type - 這是必要的設定,而且必須設定為 parameter
  • description - 參數的描述,參數會顯示在範本說明中。
  • datatype - 使用 參數時,參數值的資料類型。
  • replaces - 指定應在所有範本檔案中取代為參數值的文字值。
  • fileRename - 類似於 replaces,這會指定文字值,該值在所有範本檔案的名稱中會取代為參數值。
  • defaultValue - 當使用者未指定參數時,此參數的預設值。

使用範本時,使用者可以提供 ClassName 參數的值,而此值會取代所有出現的 StringExtensions。 如果未提供值,則會使用 defaultValue。 在此範本中,出現兩個 StringExtensionsStringExtensions.cs 檔案和 StringExtensions 類別。 因為參數的 defaultValueStringExtensions,因此如果使用範本時未指定參數,檔案名稱和類別名稱會維持不變。 當指定值 (例如 dotnet new stringext -ClassName MyExts) 時,檔案將被重新命名為 MyExts.cs,類別將被重新命名為 MyExts

若要查看範本可用的參數,請使用 -? 參數搭配範本名稱:

dotnet new stringext -?

即會產生以下輸出:

Example templates: string extensions (C#)
Author: Me

Usage:
  dotnet new stringext [options] [template options]

Options:
  -n, --name <name>       The name for the output being created. If no name is specified, the name of the output directory is used.
  -o, --output <output>   Location to place the generated output.
  --dry-run               Displays a summary of what would happen if the given command line were run if it would result in a template creation.
  --force                 Forces content to be generated even if it would change existing files.
  --no-update-check       Disables checking for the template package updates when instantiating a template.
  --project <project>     The project that should be used for context evaluation.
  -lang, --language <C#>  Specifies the template language to instantiate.
  --type <item>           Specifies the template type to instantiate.

Template options:
  -C, --ClassName <ClassName>  The name of the code file and class.
                               Type: text
                               Default: StringExtensions

您已經具備有效的 .template.config/template.json 檔案,現在您的範本已經準備好並可供安裝。 在您的終端機中,瀏覽至 extensions 資料夾,並執行下列命令以安裝位於目前資料夾中的範本:

  • 在 Windows 上dotnet new install .\
  • 在 Linux 或 MacOS 上dotnet new install ./

此命令會輸出已安裝範本的清單,其中應該會包含您的範本。

The following template packages will be installed:
   <root path>\working\content\extensions

Success: <root path>\working\content\extensions installed the following templates:
Templates                                         Short Name               Language          Tags
--------------------------------------------      -------------------      ------------      ----------------------
Example templates: string extensions              stringext                [C#]              Common/Code

測試項目範本

您已經安裝項目範本,現在請測試它。

  1. 瀏覽至 test 資料夾。

  2. 使用 dotnet new console 建立新的主控台應用程式,以便產生工作專案,供您使用 dotnet run 命令輕鬆測試。

    dotnet new console
    

    您會看到類似以下的輸出。

    The template "Console Application" was created successfully.
    
    Processing post-creation actions...
    Running 'dotnet restore' on C:\test\test.csproj...
      Restore completed in 54.82 ms for C:\test\test.csproj.
    
    Restore succeeded.
    
  3. 使用下列命令執行專案。

    dotnet run
    

    您會獲得下列輸出。

    Hello, World!
    
  4. 執行 dotnet new stringext 以從範本產生 StringExtensions.cs 檔案。

    dotnet new stringext
    

    您會獲得下列輸出。

    The template "Example templates: string extensions" was created successfully.
    
  5. 變更 Program.cs 中的程式碼,以搭配由範本所提供的擴充方法來反轉 "Hello, World!" 字串。

    Console.WriteLine("Hello, World!".Reverse());
    

    再次執行該程式,您將會看到結果已反轉。

    dotnet run
    

    您會獲得下列輸出。

    !dlroW ,olleH
    

恭喜! 您已使用 .NET 建立並部署項目範本。 為了針對此教學課程系列的下一部份做準備,請解除安裝您所建立的範本。 同時,請務必刪除 test 資料夾中的所有檔案和資料夾。 這樣就能回到最原始的狀態,並準備好進行此教學課程系列的下一個部分。

解除安裝範本

在您的終端機中,瀏覽至 extensions 資料夾,並執行下列命令,以解除安裝位於目前資料夾中的範本:

  • 在 Windows 上dotnet new uninstall .\
  • 在 Linux 或 MacOS 上dotnet new uninstall ./

此命令會輸出已解除安裝的範本清單,其中應包含您的範本。

Success: <root path>\working\content\extensions was uninstalled.

您可隨時使用 dotnet new uninstall 查看安裝的範本套件清單,每個範本套件皆包含該命令,以進行解除安裝。

下一步

在此教學課程中,您已建立項目範本。 若要了解如何建立專案範本,請繼續進行此教學課程系列。