dotnet new 自定义模板Custom templates for dotnet new

.NET Core SDK 随附了许多已安装并可供你使用的模板。The .NET Core SDK comes with many templates already installed and ready for you to use. dotnet new 命令不仅用于使用模板,还用于说明如何安装和卸载模板。The dotnet new command isn't only the way to use a template, but also how to install and uninstall templates. 自.NET Core 2.0 起,可以为任何类型的项目(如应用程序、服务、工具或类库)创建自己的自定义模板。Starting with .NET Core 2.0, you can create your own custom templates for any type of project, such as an app, service, tool, or class library. 甚至可以创建输出一个或多个独立文件(如配置文件)的模板。You can even create a template that outputs one or more independent files, such as a configuration file.

可以从任何 NuGet 源上的 NuGet 包安装自定义模板,具体方法是直接引用 NuGet .nupkg 文件,或指定包含模板的文件系统目录。You can install custom templates from a NuGet package on any NuGet feed, by referencing a NuGet .nupkg file directly, or by specifying a file system directory that contains the template. 借助模板引擎提供的功能,可以替换值、包括和排除文件,并在使用模板时执行自定义处理操作。The template engine offers features that allow you to replace values, include and exclude files, and execute custom processing operations when your template is used.

模板引擎是开放源代码,在线代码存储库位于 GitHub 上的 dotnet/templatingThe template engine is open source, and the online code repository is at dotnet/templating on GitHub. 有关模板示例,请访问 dotnet/dotnet-template-samples 存储库。Visit the dotnet/dotnet-template-samples repo for samples of templates. GitHub 上的 dotnet new 可用模板收录了更多模板,包括第三方模板。More templates, including templates from third parties, are found at Available templates for dotnet new on GitHub. 若要详细了解如何创建和使用自定义模板,请参阅如何创建自己的 dotnet new 模板dotnet/templating GitHub 存储库 WikiFor more information about creating and using custom templates, see How to create your own templates for dotnet new and the dotnet/templating GitHub repo Wiki.

若要按照演示步骤操作并创建模板,请参阅创建 dotnet new 自定义模板教程。To follow a walkthrough and create a template, see the Create a custom template for dotnet new tutorial.

.NET 默认模板.NET default templates

安装 .NET Core SDK 时,将获取十多个用于创建项目和文件的内置模板,包括控制台应用程序、类库、单元测试项目、ASP.NET Core 应用程序(包括 AngularReact 项目)和配置文件。When you install the .NET Core SDK, you receive over a dozen built-in templates for creating projects and files, including console apps, class libraries, unit test projects, ASP.NET Core apps (including Angular and React projects), and configuration files. 若要列出内置模板,请运行带有 -l|--list 选项的 dotnet new 命令:To list the built-in templates, run the dotnet new command with the -l|--list option:

dotnet new --list

ConfigurationConfiguration

模板由以下部分组成:A template is composed of the following parts:

  • 源文件和文件夹。Source files and folders.
  • 配置文件 (template.json )。A configuration file (template.json).

源文件和文件夹Source files and folders

源文件和文件夹包含运行 dotnet new <TEMPLATE> 命令时用户希望模板引擎使用的任何文件和文件夹。The source files and folders include whatever files and folders you want the template engine to use when the dotnet new <TEMPLATE> command is run. 模板引擎旨在将可运行项目 用作源代码,以生成项目。The template engine is designed to use runnable projects as source code to produce projects. 这样做有以下几个好处:This has several benefits:

  • 模板引擎不要求用户将特殊令牌注入项目的源代码。The template engine doesn't require you to inject special tokens into your project's source code.
  • 代码文件不必是特殊文件,也不必以任何方式进行修改,即可与模板引擎配合使用。The code files aren't special files or modified in any way to work with the template engine. 因此,处理项目时通常使用的工具也适用于模板内容。So, the tools you normally use when working with projects also work with template content.
  • 生成、运行和调试模板项目,就像生成、运行和调试其他任何项目一样。You build, run, and debug your template projects just like you do for any of your other projects.
  • 只需将 ./.template.config/template.json 配置文件添加到项目,即可通过现有项目快速创建模板。You can quickly create a template from an existing project just by adding a ./.template.config/template.json configuration file to the project.

模板中存储的文件和文件夹并不限于正式的 .NET 项目类型。Files and folders stored in the template aren't limited to formal .NET project types. 源文件和文件夹可能包含用户希望在使用模板时创建的任何内容,即使模板引擎仅生成一个文件作为输出也不例外。Source files and folders may consist of any content that you wish to create when the template is used, even if the template engine produces just one file as its output.

可以基于在 template.json 配置文件中提供的逻辑和设置对模板生成的文件进行修改。Files generated by the template can be modified based on logic and settings you've provided in the template.json configuration file. 用户可以将选项传递到 dotnet new <TEMPLATE> 命令以覆盖这些设置。The user can override these settings by passing options to the dotnet new <TEMPLATE> command. 自定义逻辑的一个常见示例为模板部署的代码文件中的类或变量提供名称。A common example of custom logic is providing a name for a class or variable in the code file that's deployed by a template.

template.jsontemplate.json

template.json 文件位于模板根目录中的 .template.config 文件夹。The template.json file is placed in a .template.config folder in the root directory of the template. 此文件向模板引擎提供配置信息。The file provides configuration information to the template engine. 最低配置必须包含下表中列出的成员,这足以创建功能模板。The minimum configuration requires the members shown in the following table, which is sufficient to create a functional template.

成员Member 类型Type 说明Description
$schema URIURI template.json 文件的 JSON 架构。The JSON schema for the template.json file. 如果指定架构,支持 JSON 架构的编辑器启用 JSON 编辑功能。Editors that support JSON schemas enable JSON-editing features when the schema is specified. 例如,Visual Studio Code 要求此成员启用 IntelliSense。For example, Visual Studio Code requires this member to enable IntelliSense. 使用值 http://json.schemastore.org/templateUse a value of http://json.schemastore.org/template.
author stringstring 模板创建者。The author of the template.
classifications array(string)array(string) 为了找到模板,用户可能会在搜索模板时使用的 0 个或多个模板特征。Zero or more characteristics of the template that a user might use to find the template when searching for it. 如果出现在使用 dotnet new -l|--list 命令生成的模板列表中,classifications 还会出现在“Tags” 列中。The classifications also appear in the Tags column when it appears in a list of templates produced by using the dotnet new -l|--list command.
identity stringstring 此模板的唯一名称。A unique name for this template.
name stringstring 用户应看到的模板名称。The name for the template that users should see.
shortName stringstring 方便用户选择模板的默认速记名称,适用于模板名称由用户指定(而不是通过 GUI 选择)的环境。A default shorthand name for selecting the template that applies to environments where the template name is specified by the user, not selected via a GUI. 例如,通过命令提示符和 CLI 命令使用模板时,短名称非常有用。For example, the short name is useful when using templates from a command prompt with CLI commands.

template.json 文件的完整架构位于 JSON 架构存储The full schema for the template.json file is found at the JSON Schema Store. 有关 template.json 文件的详细信息,请参阅 dotnet 创建模板 wikiFor more information about the template.json file, see the dotnet templating wiki.

示例Example

例如,下面是包含两个内容文件的模板文件夹:console.cs 和 readme.txt 。For example, here is a template folder that contains two content files: console.cs and readme.txt. 请注意,其中有包含 template.json 文件的名为 .template.config 的所需文件夹。Take notice that there is the required folder named .template.config that contains the template.json file.

└───mytemplate
    │   console.cs
    │   readme.txt
    │
    └───.template.config
            template.json

template.json 文件如下所示:The template.json file looks like the following:

{
  "$schema": "http://json.schemastore.org/template",
  "author": "Travis Chau",
  "classifications": [ "Common", "Console" ],
  "identity": "AdatumCorporation.ConsoleTemplate.CSharp",
  "name": "Adatum Corporation Console Application",
  "shortName": "adatumconsole"
}

mytemplate 文件夹是可安装的模板包。The mytemplate folder is an installable template pack. 安装此包后,shortName 可与 dotnet new 命令结合使用。Once the pack is installed, the shortName can be used with the dotnet new command. 例如,dotnet new adatumconsole 会将 console.csreadme.txt 文件输出到当前文件夹。For example, dotnet new adatumconsole would output the console.cs and readme.txt files to the current folder.

将模板打包到 NuGet 包(nupkg 文件)Packing a template into a NuGet package (nupkg file)

自定义模板与 dotnet pack 命令和 .csproj 文件一起打包。A custom template is packed with the dotnet pack command and a .csproj file. 或者,NuGet 可与 nuget pack 命令以及 .nuspec 文件一起使用。Alternatively, NuGet can be used with the nuget pack command along with a .nuspec file. 但是,NuGet 在 Windows 上需要 .NET Framework,在 Linux 和 MacOS 上需要 MonoHowever, NuGet requires the .NET Framework on Windows and Mono on Linux and MacOS.

该 .csproj 文件与传统代码项目 .csproj 文件略有不同。The .csproj file is slightly different from a traditional code-project .csproj file. 请注意以下设置:Note the following settings:

  1. 添加 <PackageType> 设置并将其设为 TemplateThe <PackageType> setting is added and set to Template.
  2. 添加 <PackageVersion> 设置并将其设为有效的 NuGet 版本号The <PackageVersion> setting is added and set to a valid NuGet version number.
  3. 添加 <PackageId> 设置并将其设为唯一标识符。The <PackageId> setting is added and set to a unique identifier. 此标识符用于卸载模板包,NuGet 源用它来注册你的模板包。This identifier is used to uninstall the template pack and is used by NuGet feeds to register your template pack.
  4. 应设置泛型元数据设置:<Title><Authors><Description><PackageTags>Generic metadata settings should be set: <Title>, <Authors>, <Description>, and <PackageTags>.
  5. 必须设置 <TargetFramework> 设置,即使未使用模板过程生成的二进制文件也必须设置。The <TargetFramework> setting must be set, even though the binary produced by the template process isn't used. 在下面的示例中,它设置为 netstandard2.0In the example below it's set to netstandard2.0.

.nupkg NuGet 包形式的模板包要求所有模板都存储在包中的 content 文件夹中。A template pack, in the form of a .nupkg NuGet package, requires that all templates be stored in the content folder within the package. 还有几个设置将添加到 .csproj 文件以确保生成的 .nupkg 作为模板包安装:There are a few more settings to add to a .csproj file to ensure that the generated .nupkg can be installed as a template pack:

  1. <IncludeContentInPack> 设置设为 true 以包含项目在 NuGet 包中设为“内容”的任何文件 。The <IncludeContentInPack> setting is set to true to include any file the project sets as content in the NuGet package.
  2. <IncludeBuildOutput> 设置设为 false 以从 NuGet 包排除编译器生成的所有二进制文件。The <IncludeBuildOutput> setting is set to false to exclude all binaries generated by the compiler from the NuGet package.
  3. <ContentTargetFolders> 设置设为 contentThe <ContentTargetFolders> setting is set to content. 这可确保设为“内容” 的文件存储在 NuGet 包的 content 文件夹中。This makes sure that the files set as content are stored in the content folder in the NuGet package. NuGet 包中的此文件夹由 dotnet 模板系统解析。This folder in the NuGet package is parsed by the dotnet template system.

使所有代码文件不被模板项目编译的一个简单的方法是使用 <ItemGroup> 元素内项目文件中的 <Compile Remove="**\*" /> 项。An easy way to exclude all code files from being compiled by your template project is by using the <Compile Remove="**\*" /> item in your project file, inside an <ItemGroup> element.

设置模板包结构的一个简单方法是将所有模板放在单独的文件夹中,然后放到位于 .csproj 文件所在目录的 templates 文件夹的每个模板文件夹中 。An easy way to structure your template pack is to put all templates in individual folders, and then each template folder inside of a templates folder that is located in the same directory as your .csproj file. 这样,你可以使用单个项目项包括 templates 中的所有文件和文件夹作为“内容” 。This way, you can use a single project item to include all files and folders in the templates as content. <ItemGroup> 元素中创建 <Content Include="templates\**\*" Exclude="templates\**\bin\**;templates\**\obj\**" /> 项。Inside of an <ItemGroup> element, create a <Content Include="templates\**\*" Exclude="templates\**\bin\**;templates\**\obj\**" /> item.

下面是一个遵循上述所有准则的示例 .csproj 文件。Here is an example .csproj file that follows all of the guidelines above. 它将 templates 子文件夹打包为“内容” 包文件夹,并使所有代码文件都不被编译。It packs the templates child folder to the content package folder and excludes any code file from being compiled.

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

  <PropertyGroup>
    <PackageType>Template</PackageType>
    <PackageVersion>1.0</PackageVersion>
    <PackageId>AdatumCorporation.Utility.Templates</PackageId>
    <Title>AdatumCorporation Templates</Title>
    <Authors>Me</Authors>
    <Description>Templates to use when creating an application for Adatum Corporation.</Description>
    <PackageTags>dotnet-new;templates;contoso</PackageTags>
    <TargetFramework>netstandard2.0</TargetFramework>

    <IncludeContentInPack>true</IncludeContentInPack>
    <IncludeBuildOutput>false</IncludeBuildOutput>
    <ContentTargetFolders>content</ContentTargetFolders>
  </PropertyGroup>

  <ItemGroup>
    <Content Include="templates\**\*" Exclude="templates\**\bin\**;templates\**\obj\**" />
    <Compile Remove="**\*" />
  </ItemGroup>

</Project>

以下示例演示使用 .csproj 创建模板包的文件和文件夹结构。The example below demonstrates the file and folder structure of using a .csproj to create a template pack. MyDotnetTemplates.csproj 文件和 templates 文件夹都位于名为 project_folder 的根目录中。The MyDotnetTemplates.csproj file and templates folder are both located at the root of a directory named project_folder. templates 文件夹包含两个模板 mytemplate1 和 mytemplate2 。The templates folder contains two templates, mytemplate1 and mytemplate2. 每个模板具有内容文件和包含 template.json 配置文件的 .template.config 文件夹。Each template has content files and a .template.config folder with a template.json config file.

project_folder
│   MyDotnetTemplates.csproj
│
└───templates
    ├───mytemplate1
    │   │   console.cs
    │   │   readme.txt
    │   │
    │   └───.template.config
    │           template.json
    │
    └───mytemplate2
        │   otherfile.cs
        │
        └───.template.config
                template.json

安装模板Installing a template

使用 dotnet new -i|--install 命令以安装包。Use the dotnet new -i|--install command to install a package.

从 nuget.org 中存储的 NuGet 包安装模板的具体步骤To install a template from a NuGet package stored at nuget.org

使用 NuGet 包标识符安装模板包。Use the NuGet package identifier to install a template package.

dotnet new -i <NUGET_PACKAGE_ID>

从本地 nupkg 文件安装模板的具体步骤To install a template from a local nupkg file

提供指向 .nupkg NuGet 包文件的路径。Provide the path to a .nupkg NuGet package file.

dotnet new -i <PATH_TO_NUPKG_FILE>

从文件系统目录安装模板的具体步骤To install a template from a file system directory

模板可从模板文件夹安装,如以上示例中的 mytemplate1 文件夹。Templates can be installed from a template folder, such as the mytemplate1 folder from the example above. 指定 .template.config 文件夹的文件夹路径。Specify the folder path of the .template.config folder. 模板目录的路径不需要是绝对路径。The path to the template directory does not need to be absolute. 但是,卸载从文件夹安装的模板时需要绝对路径。However, an absolute path is required to uninstall a template that is installed from a folder.

dotnet new -i <FILE_SYSTEM_DIRECTORY>

获取已安装模板的列表Get a list of installed templates

在没有任何其他参数的情况下,卸载命令将列出所有已安装的模板。The uninstall command, without any other parameters, will list all installed templates.

dotnet new -u

该命令返回如下所示的输出:That command returns something similar to the following output:

Template Instantiation Commands for .NET Core CLI

Currently installed items:
  Microsoft.DotNet.Common.ItemTemplates
    Templates:
      global.json file (globaljson)
      NuGet Config (nugetconfig)
      Solution File (sln)
      Dotnet local tool manifest file (tool-manifest)
      Web Config (webconfig)
  Microsoft.DotNet.Common.ProjectTemplates.3.0
    Templates:
      Class library (classlib) C#
      Class library (classlib) F#
      Class library (classlib) VB
      Console Application (console) C#
      Console Application (console) F#
      Console Application (console) VB
...

Currently installed items: 后面的第一级项是用于卸载模板的标识符。The first level of items after Currently installed items: are the identifiers used in uninstalling a template. 在上述示例中,列出了 Microsoft.DotNet.Common.ItemTemplatesMicrosoft.DotNet.Common.ProjectTemplates.3.0And in the example above, Microsoft.DotNet.Common.ItemTemplates and Microsoft.DotNet.Common.ProjectTemplates.3.0 are listed. 如果使用文件系统路径安装模板,此标识符将是 .template.config 文件夹的文件夹路径。If the template was installed by using a file system path, this identifier will the folder path of the .template.config folder.

卸载模板Uninstalling a template

使用 dotnet new -u|--uninstall 命令卸载包。Use the dotnet new -u|--uninstall command to uninstall a package.

如果通过 NuGet 源或直接通过 .nupkg 文件安装包,请提供标识符。If the package was installed by either a NuGet feed or by a .nupkg file directly, provide the identifier.

dotnet new -u <NUGET_PACKAGE_ID>

如果通过指定 .template.config 文件夹的路径安装包,请使用该绝对 路径卸载包。If the package was installed by specifying a path to the .template.config folder, use that absolute path to uninstall the package. 你可以在 dotnet new -u 命令提供的输出中看到模板的绝对路径。You can see the absolute path of the template in the output provided by the dotnet new -u command. 有关详细信息,请参阅上文的获取已安装的模板列表部分。For more information, see the Get a list of installed templates section above.

dotnet new -u <ABSOLUTE_FILE_SYSTEM_DIRECTORY>

使用自定义模板创建项目Create a project using a custom template

安装模板后,通过执行 dotnet new <TEMPLATE> 命令来使用模板,就像使用其他任何预安装模板一样。After a template is installed, use the template by executing the dotnet new <TEMPLATE> command as you would with any other pre-installed template. 还可以为 dotnet new 命令指定选项,包括在模板设置中配置的模板专用选项。You can also specify options to the dotnet new command, including template-specific options you configured in the template settings. 直接向命令提供模板的短名称:Supply the template's short name directly to the command:

dotnet new <TEMPLATE>

请参阅See also