教學課程:建立項目範本Tutorial: Create an item template

透過 .NET Core,您可以建立及部署能產生專案、檔案,甚至是資源的範本。With .NET Core, you can create and deploy templates that generate projects, files, even resources. 此教學課程是指導您如何建立、安裝及解除安裝能搭配 dotnet new 命令使用之範的本系列文章第一部分。This tutorial is part one of a series that teaches you how to create, install, and uninstall, templates for use with the dotnet new command.

在這部分的系列文章中,您將了解如何:In this part of the series, you'll learn how to:

  • 針對項目範本建立類別Create a class for an item template
  • 建立範本設定資料夾和檔案Create the template config folder and file
  • 從檔案路徑安裝範本Install a template from a file path
  • 測試項目範本Test an item template
  • 將項目範本解除安裝Uninstall an item template

必要條件Prerequisites

  • .NET Core 2.2 SDK 或更新版本。.NET Core 2.2 SDK or later versions.

  • 請參閱參考文章 dotnet new 的自訂範本Read the reference article Custom templates for dotnet new.

    該參考文章會說明範本的基本概念及構成方式。The reference article explains the basics about templates and how they're put together. 那些資訊有一部分會在此重述。Some of this information will be reiterated here.

  • 開啟終端機並瀏覽至 working\templates\ 資料夾。Open a terminal and navigate to the working\templates\ folder.

建立必要的資料夾Create the required folders

本系列文章會使用「工作資料夾」來存放您的範本來源,並使用「測試資料夾」來測試您的範本。This series uses a "working folder" where your template source is contained and a "testing folder" used to test your templates. 工作資料夾和測試資料夾應該放在相同的父資料夾中。The working folder and testing folder should be under the same parent folder.

首先,請建立父資料夾;其名稱並不重要。First, create the parent folder, the name does not matter. 然後,建立名為 working 的子資料夾。Then, create a subfolder named working. working 資料夾中,建立名為 templates 的子資料夾。Inside of the working folder, create a subfolder named templates.

接下來,在父資料夾底下建立名為 test 的資料夾。Next, create a folder under the parent folder named test. 資料夾結構看起來應如下所示:The folder structure should look like the following:

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

建立項目範本Create an item template

項目範本是特定類型的範本,其會包含一或多個檔案。An item template is a specific type of template that contains one or more files. 這些範本類型很適合在您想要產生設定、程式碼或方案檔之類的項目時使用。These types of templates are useful when you want to generate something like a config, code, or solution file. 在此範例中,您將會建立能將擴充方法加入字串類型的類別。In this example, you'll create a class that adds an extension method to the string type.

在您的終端機中,瀏覽至 working\templates\ 資料夾,並建立名為 extensions 的新子資料夾。In your terminal, navigate to the working\templates\ folder and create a new subfolder named extensions. 進入該資料夾。Enter the folder.

working
└───templates
    └───extensions

建立名為 CommonExtensions.cs 的新檔案,並使用您慣用的文字編輯器開啟它。Create a new file named CommonExtensions.cs and open it with your favorite text editor. 此類別將會提供名為 Reverse 的擴充方法,其能反轉字串的內容。This class will provide an extension method named Reverse that reverses the contents of a string. 貼上下列程式碼並儲存檔案:Paste in the following code and save the file:

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);
        }
    }
}

您已經建立範本的內容,現在您需要在範本的根資料夾建立範本設定。Now that you have the content of the template created, you need to create the template config at the root folder of the template.

建立範本設定Create the template config

.NET Core 會將範本辨識為存在於範本根目錄中的特殊資料夾及設定檔。Templates are recognized in .NET Core by a special folder and config file that exist at the root of your template. 在此教學課程中,您的範本資料夾是位於 working\templates\extensions\In this tutorial, your template folder is located at working\templates\extensions\.

當您建立範本時,範本資料夾中的所有檔案和資料夾都會包含為範本的一部分,除了特殊設定資料夾之外。When you create a template, all files and folders in the template folder are included as part of the template except for the special config folder. 此設定資料夾名為 .template.configThis config folder is named .template.config.

首先,建立名為 .template.config 的新子資料夾,然後進入它。First, create a new subfolder named .template.config, enter it. 然後,建立名為 template.json 的新檔案。Then, create a new file named template.json. 您的資料夾結構看起來應該像這樣:Your folder structure should look like this:

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

使用您慣用的文字編輯器開啟 template.json,然後貼上下列 JSON 程式碼並儲存它:Open the template.json with your favorite text editor and paste in the following JSON code and save it:

{
  "$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"
  }
}

此設定檔會包含您範本的所有設定。This config file contains all the settings for your template. 您可以看見基本設定 (例如 nameshortName),但還有設定為 itemtags/type 值。You can see the basic settings, such as name and shortName, but there's also a tags/type value that is set to item. 這會將您的範本分類為項目範本。This categorizes your template as an item template. 您可以建立的範本類型本身並無限制。There's no restriction on the type of template you create. itemproject 值是 .NET Core 建議的常用名稱,它們可以讓使用者輕鬆篩選其想要尋找的範本類型。The item and project values are common names that .NET Core recommends so that users can easily filter the type of template they're searching for.

classifications 項目代表您執行 dotnet new 並取得範本清單時所會看見的 [標籤] 欄。The classifications item represents the tags column you see when you run dotnet new and get a list of templates. 使用者也可以根據分類標籤搜尋。Users can also search based on classification tags. 不要將 *.json 檔案中的 tags 屬性與 classifications 標籤清單混淆在一起。Don't confuse the tags property in the *.json file with the classifications tags list. 它們是不同的東西,但不幸地具有類似的名稱。They're two different things unfortunately named similarly. template.json 檔案的完整結構描述位於 JSON 結構描述存放區The full schema for the template.json file is found at the JSON Schema Store. 如需 template.json 檔案的詳細資訊,請參閱 dotnet 範本化 Wiki (英文)。For more information about the template.json file, see the dotnet templating wiki.

您已經具備有效的 .template.config/template.json 檔案,現在您的範本已經準備好並可供安裝。Now that you have a valid .template.config/template.json file, your template is ready to be installed. 在您的終端機中,瀏覽至 extensions 資料夾,並執行下列命令以安裝位於目前資料夾中的範本:In your terminal, navigate to the extensions folder and run the following command to install the template located at the current folder:

  • 在 Windows 上dotnet new -i .\On Windows: dotnet new -i .\
  • 在 Linux 或 MacOS 上dotnet new -i ./On Linux or macOS: dotnet new -i ./

此命令會輸出已安裝範本的清單,其中應該會包含您的範本。This command outputs the list of templates installed, which should include yours.

C:\working\templates\extensions> dotnet new -i .\
Usage: new [options]

Options:
  -h, --help          Displays help for this command.
  -l, --list          Lists templates containing the specified name. If no name is specified, lists all templates.

... cut to save space ...

Templates                                         Short Name            Language          Tags
-------------------------------------------------------------------------------------------------------------------------------
Example templates: string extensions              stringext             [C#]              Common/Code
Console Application                               console               [C#], F#, VB      Common/Console
Class library                                     classlib              [C#], F#, VB      Common/Library
WPF Application                                   wpf                   [C#], VB          Common/WPF
Windows Forms (WinForms) Application              winforms              [C#], VB          Common/WinForms
Worker Service                                    worker                [C#]              Common/Worker/Web

測試項目範本Test the item template

您已經安裝項目範本,現在請測試它。Now that you have an item template installed, test it. 瀏覽至 test/ 資料夾並使用 dotnet new console 建立新的主控台應用程式。Navigate to the test/ folder and create a new console application with dotnet new console. 這會產生工作專案,其可讓您使用 dotnet run 命令輕鬆地進行測試。This generates a working project you can easily test with the dotnet run command.

C:\test> 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.
C:\test> dotnet run
Hello World!

接下來,執行 dotnet new stringext 以從範本產生 CommonExtensions.csNext, run dotnet new stringext to generate the CommonExtensions.cs from the template.

C:\test> dotnet new stringext
The template "Example templates: string extensions" was created successfully.

變更 Program.cs 中的程式碼,以搭配由範本所提供的擴充方法來反轉 "Hello World" 字串。Change the code in Program.cs to reverse the "Hello World" string with the extension method provided by the template.

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

再次執行該程式,您將會看到結果已被反轉。Run the program again and you'll see that the result is reversed.

C:\test> dotnet run
!dlroW olleH

恭喜您!Congratulations! 您已透過 .NET Core 建立並部署項目範本。You created and deployed an item template with .NET Core. 為了針對此教學課程系列的下一部份做準備,您必須將您所建立的範本解除安裝。In preparation for the next part of this tutorial series, you must uninstall the template you created. 同時,請務必刪除 test 資料夾中的所有檔案。Make sure to delete all files from the test folder too. 這能讓您回到最原始的狀態,並準備好進行此教學課程的下一個主要區段。This will get you back to a clean state ready for the next major section of this tutorial.

解除安裝範本Uninstall the template

由於您是依檔案路徑來安裝範本,您必須使用絕對檔案路徑來將它解除安裝。Because you installed the template by file path, you must uninstall it with the absolute file path. 您可以透過執行 dotnet new -u 命令來查看已安裝範本的清單。You can see a list of templates installed by running the dotnet new -u command. 您的範本應該會被列在最後。Your template should be listed last. 使用列出的路徑來搭配 dotnet new -u <ABSOLUTE PATH TO TEMPLATE DIRECTORY> 命令將您的範本解除安裝。Use the path listed to uninstall your template with the dotnet new -u <ABSOLUTE PATH TO TEMPLATE DIRECTORY> command.

C:\working> dotnet new -u
Template Instantiation Commands for .NET Core CLI

Currently installed items:
  Microsoft.DotNet.Common.ItemTemplates
    Templates:
      dotnet gitignore file (gitignore)
      global.json file (globaljson)
      NuGet Config (nugetconfig)
      Solution File (sln)
      Dotnet local tool manifest file (tool-manifest)
      Web Config (webconfig)

... cut to save space ...

  NUnit3.DotNetNew.Template
    Templates:
      NUnit 3 Test Project (nunit) C#
      NUnit 3 Test Item (nunit-test) C#
      NUnit 3 Test Project (nunit) F#
      NUnit 3 Test Item (nunit-test) F#
      NUnit 3 Test Project (nunit) VB
      NUnit 3 Test Item (nunit-test) VB
  C:\working\templates\extensions
    Templates:
      Example templates: string extensions (stringext) C#
C:\working> dotnet new -u C:\working\templates\extensions

後續步驟Next steps

在此教學課程中,您已建立項目範本。In this tutorial, you created an item template. 若要了解如何建立專案範本,請繼續進行此教學課程系列。To learn how to create a project template, continue this tutorial series.