教學課程:建立專案範本

透過 .NET,您可以建立及部署範本,以產生專案、檔案,甚至是資源。 本教學課程是一系列的第一部分,會教導您如何建立、安裝和卸載範本,以搭配 dotnet new 命令使用。

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

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

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

必要條件

  • .NET SDK 7.0.100 或更新版本。

  • 請參閱參考文章 dotnet new 的自訂範本

    該參考文章會說明範本的基本概念及構成方式。 那些資訊有一部分會在此重述。

  • 開啟終端機並瀏覽至 working\templates 資料夾。

重要

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

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

建立必要的資料夾

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

首先,請建立父資料夾;其名稱並不重要。 然後,建立名為 working 的子資料夾。 在 working 資料夾中,建立名為 templates 的子資料夾。

接下來,在父資料夾底下建立名為 test 的資料夾。 資料夾結構看起來應該如下所示。

parent_folder
├───test
└───working
    └───templates

建立項目範本

項目範本是特定類型的範本,其會包含一或多個檔案。 這些範本類型很適合在您想要產生設定、程式碼或方案檔之類的項目時使用。 在此範例中,您將會建立能將擴充方法加入字串類型的類別。

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

working
└───templates
    └───extensions

建立名為 CommonExtensions.cs 的新檔案,並使用您慣用的文字編輯器開啟它。 此類別將會提供名為 Reverse 的擴充方法,其能反轉字串的內容。 貼上下列程式碼並儲存檔案:

using System;

namespace System
{
    public static class StringExtensions
    {
        public static string Reverse(this string value)
        {
            var tempArray = value.ToCharArray();
            Array.Reverse(tempArray);
            return new string(tempArray);
        }
    }
}

您已經建立範本的內容,現在您需要在範本的根資料夾建立範本設定。

建立範本設定

範本是由存在於範本根目錄的特殊資料夾和組態檔所辨識。 在此教學課程中,您的範本資料夾是位於 working\templates\extensions

當您建立範本時,範本資料夾中的所有檔案和資料夾都會包含為範本的一部分,除了特殊設定資料夾之外。 此設定資料夾名為 .template.config

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

working
└───templates
    └───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 建議的常見名稱,讓使用者可以輕鬆地篩選他們搜尋的範本類型。

symbols這個 JSON 物件的部分是用來定義可在範本中使用的參數。 在此情況下,有一個參數已定義 , ClassName 其具有數個屬性。 屬性 type 指定這是參數、 description 屬性提供參數的描述、 datatype 屬性指定此參數的值應該是文字、屬性指定應該由此參數值取代的文字、 replacesfileRename 屬性指定應該使用此參數的值重新命名檔案、 defaultValue 和 屬性會指定此參數的預設值。 這表示使用此範本時,使用者可以提供 參數的值 ClassName ,而這個值將用來取代範本中的所有專案 StringExtensions ,以及重新命名檔案。 如果未提供任何值,則會 StringExtensions 使用 作為預設值。 若要查看專案範本可評估哪些參數,使用者可以執行 dotnet new stringext -? 以查看可評估的參數。

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

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

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

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

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

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

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

測試項目範本

您已經安裝項目範本,現在請測試它。 瀏覽至 test/ 資料夾並使用 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.

使用 執行專案。

dotnet run

您會收到下列輸出。

Hello, World!

接下來,執行 dotnet new stringext 以從範本產生 CommonExtensions.cs

dotnet new stringext

您會收到下列輸出。

The template "Example templates: string extensions" was created successfully.

變更 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\templates\extensions was uninstalled.

您可以隨時使用 dotnet new uninstall 來查看已安裝的範本套件清單,包括命令卸載的每個範本套件。

下一步

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