教學課程:建立專案範本Tutorial: Create a project template

透過 .NET Core,您可以建立及部署能產生專案、檔案,甚至是資源的範本。With .NET Core, you can create and deploy templates that generate projects, files, even resources. 此教學課程是指導您如何建立、安裝及解除安裝能搭配 dotnet new 命令使用之範的本系列文章第二部分。This tutorial is part two 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 the resources of a project template
  • 建立範本設定資料夾和檔案Create the template config folder and file
  • 從檔案路徑安裝範本Install a template from a file path
  • 測試項目範本Test an item template
  • 將項目範本解除安裝Uninstall an item template

PrerequisitesPrerequisites

  • 完成此教學課程系列的第 1 部分Complete part 1 of this tutorial series.
  • 開啟終端機並瀏覽至 working\templates\ 資料夾。Open a terminal and navigate to the working\templates\ folder.

建立專案範本Create a project template

專案範本能產生可立即執行的專案,讓使用者能以一組已可運作的程式碼來輕鬆開始。Project templates produce ready-to-run projects that make it easy for users to start with a working set of code. .NET Core 包含幾個專案範本,例如主控台應用程式或類別庫。.NET Core includes a few project templates such as a console application or a class library. 在此範例中,您將會建立新的主控台專案,其能啟用 C# 8.0 並產生 async main 進入點。In this example, you'll create a new console project that enables C# 8.0 and produces an async main entry point.

在您的終端機中,瀏覽至 working\templates\ 資料夾,並建立名為 consoleasync 的新子資料夾。In your terminal, navigate to the working\templates\ folder and create a new subfolder named consoleasync. 進入該子資料夾,然後執行 dotnet new console 以產生標準主控台應用程式。Enter the subfolder and run dotnet new console to generate the standard console application. 您將會編輯由此範本所產生的檔案來建立新的範本。You'll be editing the files produced by this template to create a new template.

working
└───templates
    └───consoleasync
            consoleasync.csproj
            Program.cs

修改 Program.csModify Program.cs

開啟 program.cs 檔案。Open up the program.cs file. 該主控台專案不會使用非同步進入點,因次讓我們來加入它。The console project doesn't use an asynchronous entry point, so let's add that. 將程式碼變更為下列程式碼,然後儲存檔案:Change your code to the following and save the file:

using System;
using System.Threading.Tasks;

namespace consoleasync
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await Console.Out.WriteAsync("Hello World with C# 8.0!");
        }
    }
}

修改 consoleasync.csprojModify consoleasync.csproj

讓我們將專案使用的 C# 語言版本更新為 8.0 版。Let's update the C# language version the project uses to version 8.0. 編輯 consoleasync.csproj 檔案並將 <LangVersion> 設定加入 <PropertyGroup> 節點。Edit the consoleasync.csproj file and add the <LangVersion> setting to a <PropertyGroup> node.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>

    <LangVersion>8.0</LangVersion>

  </PropertyGroup>
  
</Project>

建置專案Build the project

在您完成專案範本之前,您應該測試它以確保其能正確編譯及執行。Before you complete a project template, you should test it to make sure it compiles and runs correctly. 在終端機中執行 dotnet run 命令,您應該會看見下列輸出:In your terminal, run the dotnet run command and you should see the following output:

C:\working\templates\consoleasync> dotnet run
Hello World with C# 8.0!

您可以將使用 dotnet run 所建立的 objbin 資料夾刪除。You can delete the obj and bin folders created by using dotnet run. 刪除這些檔案能確保您的範本只會包含與範本相關的檔案,而不會包含因建置動作而產生的任何檔案。Deleting these files ensures your template only includes the files related to your template and not any files that result of a build action.

您已經建立範本的內容,現在您需要在範本的根資料夾建立範本設定。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\consoleasync\In this tutorial, your template folder is located at working\templates\consoleasync\.

當您建立範本時,範本資料夾中的所有檔案和資料夾都會包含為範本的一部分,除了特殊設定資料夾之外。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
    └───consoleasync
        └───.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", "Console", "C#8" ],
  "identity": "ExampleTemplate.AsyncProject",
  "name": "Example templates: async project",
  "shortName": "consoleasync",
  "tags": {
    "language": "C#",
    "type": "project"
  }
}

此設定檔會包含您範本的所有設定。This config file contains all of the settings for your template. 您可以看見基本設定 (例如 nameshortName),但還有設定為 projecttags/type 值。You can see the basic settings such as name and shortName but also there's a tags/type value that's set to project. 這會將您的範本指定為專案範本。This designates your template as a project 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. 在您安裝範本之前,請確定您已將不想要包含在範本中的所有額外檔案資料夾和檔案刪除,例如 binobj 資料夾。Before you install the template, make sure that you delete any extra files folders and files you don't want included in your template, like the bin or obj folders. 在您的終端機中,瀏覽至 consoleasync 資料夾,並執行 dotnet new -i .\ 以安裝位於目前資料夾中的範本。In your terminal, navigate to the consoleasync folder and run dotnet new -i .\ to install the template located at the current folder. 如果您是使用 Linux 或 MacOS 作業系統,請使用正斜線:dotnet new -i ./If you're using a Linux or MacOS operating system, use a forward slash: dotnet new -i ./.

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

C:\working\templates\consoleasync> 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
-------------------------------------------------------------------------------------------------------------------------------
Console Application                               console               [C#], F#, VB      Common/Console
Example templates: async project                  consoleasync          [C#]              Common/Console/C#8
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 project template

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

C:\test> dotnet new consoleasync
The template "Example templates: async project" was created successfully.
C:\test> dotnet run
Hello World with C# 8.0!

恭喜您!Congratulations! 您已透過 .NET Core 建立並部署專案範本。You created and deployed a project 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 using a 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\consoleasync
    Templates:
      Example templates: async project (consoleasync) C#
C:\working> dotnet new -u C:\working\templates\consoleasync

後續步驟Next steps

在此教學課程中,您已建立專案範本。In this tutorial, you created a project template. 若要了解如何將項目和專案範本封裝為易於使用的單一檔案,請繼續進行此教學課程系列。To learn how to package both the item and project templates into an easy-to-use file, continue this tutorial series.