教程:创建项模板

使用 .NET,可以创建和部署生成项目、文件和资源的模板。 本教程是一系列教程的第一部分,介绍如何创建、安装和卸载模板以用于 dotnet new 命令。

可以在 .NET 示例 GitHub 存储库中查看已完成的模板。

小窍门

在 Visual Studio 的“添加新项”对话框中不显示项目模板

在本系列的这一部分中,你将了解如何:

  • 为项模板创建类。
  • 创建模板配置文件夹和文件。
  • 从文件路径安装模板。
  • 测试项目模板。
  • 卸载项模板。

先决条件

  • .NET 9 或更高版本。

  • 参考文章介绍了有关模板的基础知识及其组合方式。 此处重申了其中一些信息。

  • 打开终端并导航到要在其中存储和测试模板的文件夹。

创建所需的文件夹

此系列使用包含模板源的“工作文件夹”和用于测试模板的“测试文件夹”。 工作文件夹和测试文件夹应在同一父文件夹下。

首先,创建父文件夹,名称并不重要。 然后,创建两个名为 “工作 ”和 “测试”的子文件夹。 在 工作 文件夹内,创建名为 内容的子文件夹。

文件夹结构应如下所示。

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

创建项目模板

项模板是包含一个或多个文件的特定模板类型。 当已有项目并且想要生成另一个文件(如配置文件或代码文件)时,这些类型的模板非常有用。 在此示例中,将创建一个类,该类将扩展方法添加到字符串类型。

在终端中,导航到 working\content 文件夹,并创建新的名为 extensions 的子文件夹。

working
└───content
    └───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,但也存在一个 tags/type 设置为 item的值。 这会将模板分类为“项”模板。 对创建的模板类型没有限制。 itemproject值是.NET建议的常用名称,以便用户可以轻松筛选他们正在搜索的模板类型。

该项classifications表示运行并获取模板列表时看到的dotnet new列。 用户还可以基于分类标记进行搜索。 不要将template.json文件中的tags属性与classifications混淆。 它们是两个不同的概念,不幸地命名为相同。 template.json 文件的完整架构位于 JSON 架构存储中,并在 template.json参考中介绍。 有关 template.json 文件的详细信息,请参阅 dotnet 模板化 wiki

symbols此 JSON 对象的部分用于定义可在模板中使用的参数。 在这种情况下,定义了一个参数 ClassName。 定义的参数包含以下设置:

  • type - 这是一个强制设置,必须设置为 parameter
  • description - 参数的说明,该参数将在模板帮助文档中显示。
  • datatype - 使用参数时参数值的数据类型。
  • replaces - 指定应在所有模板文件中由参数值替换的文本。
  • fileRename - 类似于 replaces,这指定一个文本值,该文本值在所有模板文件的名称中被参数值替换。
  • defaultValue - 如果用户未指定此参数,则此参数的默认值。

使用模板时,用户可以为 ClassName 参数提供值,此值将替换所有匹配项 StringExtensions。 如果未提供值,则使用该值 defaultValue 。 对于此模板,有两次出现 StringExtensions:文件 StringExtensions.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 文件后,模板即可安装。 在终端中,导航到 扩展 文件夹并运行以下命令以安装位于当前文件夹的模板:

  • 在 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. 导航到 测试 文件夹。

  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 创建并部署了项模板。 为准备本教程系列的下一部分,请卸载创建的模板。 请确保也删除 测试 文件夹中的所有文件和文件夹。 这将使你恢复到整洁的状态,为接下来教程系列的部分做好准备。

卸载模板

在终端中,导航到 扩展 文件夹并运行以下命令以卸载位于当前文件夹的模板:

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

此命令输出卸载的模板列表,其中应包括你的模板。

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

随时可以使用 dotnet new uninstall 查看已安装模板包的列表,其中包括每个模板包的卸载命令。

后续步骤

在本教程中,你创建了一个项模板。 若要了解如何创建项目模板,请继续学习本教程系列。