使用.Net Core CLI命令dotnet new创建自定义模板

2022-10-17,,,,

文章起源来自一篇博客:使用 .net core 创建 项目模板,模板项目,template - deepthought - 博客园
之前使用abp的时候就很认同abp创建模板项目的方式。想不到.net core出了更赞的方式创建模板。之前写过一个系列文章,有不少对abp框架的改动(见文章:基于.netcore和abp框架如何让windows服务执行quartz定时作业 - repeatedly - 博客园),如果将其加入自定义模板,应该是一个不错的想法。
本篇文章就对该项目着手改造。项目代码地址:dotnetcore_practice/abp.windowsservice at master · puzzledalien/dotnetcore_practice

系统必备

.net core 2.2 sdk 或更高版本。

搭建模板项目

因为是对现有的项目改造,将其作为模板进行改造,所以就直接在原有的项目上处理。私以为实际项目使用的话,可以创建一个目录名为abpwindowsservicetemplate,然后将项目拷贝进去。不多废话了。

  1. 建立文件夹,名为.template.config
  2. 在该文件下,创建文件template.json
  3. 打开文件,模板配置内容如下
{
 "$schema": "http://json.schemastore.org/template",
 "author": "templateauthor",
 "classifications": [ "console","webapi" ],
 "name": "myjobtemplate",
 "identity": "myjobtemplate",
 "groupidentity": "myjobtemplate",
 "shortname": "jt",
 "tags": {
   "language": "c#",
   "type": "project"
 },
 "sourcename": "myjob",
 "prefernamedirectory": true
}

保存配置之后,这就算搭建成功。当然这是搭建一个项目的最基本配置,详细配置参考请查阅

基础配置说明

  • $schema:template.json 文件的 json 架构。默认值使用http://json.schemastore.org/template
  • author:模板作者
  • classifications:模板特征标识。上文举例的配置是因为我自定义的模板包括了console和webapi。
  • identity:此模板的唯一名称
  • name:用户看到的模板名称
  • shortname:短名称。当使用cli命令创建模板项目时,使用短名称将利于使用。
  • sourcename:模板替换的关键文本,使用时需要注意,要选择合适的替换文本,不然容易误伤代码。

如何使用

本地安装模板

在文件夹.template.config所在目录执行命令

dotnet  new  -i  .

上面的命令使用的是相对路径进行安装,还可以使用绝对路径安装。先卸载再尝试一下绝对路径安装。

卸载模板

执行卸载命令

dotnet new -u

执行之后可以看到罗列处理的所有已经安装的模板,以及相应的卸载命令。找到需要卸载的模板,类似下文。

 d:\github\dotnetcore_practice\abp.windowsservice
    templates:
      myjobtemplate (jt) c#
    uninstall command:
      dotnet new -u d:\github\dotnetcore_practice\abp.windowsservice

执行卸载命令

dotnet new -u d:\github\dotnetcore_practice\abp.windowsservice

结果如下,卸载成功,可以通过命令dotnet new -l查看是否卸载成功

ps d:\testtemplate> dotnet new -u d:\github\dotnetcore_practice\abp.windowsservice\demo.myjob
ps d:\testtemplate>

绝对路径安装

卸载模板之后,尝试绝对路径安装模板。尝试如下,安装成功

ps d:\testtemplate> dotnet new -i d:\github\dotnetcore_practice\abp.windowsservice\demo.myjob

命令生成项目

ps d:\testtemplate> dotnet new jt -n test -o .
the template "myjobtemplate" was created successfully.

jt是模板配置文件中指定的shortname。
-n指定的是将项目中出现的所有文本myjob替换为test,因为配置中sourcename是myjob,可按需配置。
-o指定的是生成项目输出目录,上述命令生成项目输出到了d:\testtemplate

参考

  • 使用 .net core 创建 项目模板,模板项目,template - deepthought - 博客园
  • home · dotnet/templating wiki
  • dotnet new 自定义模板 - .net core cli | microsoft docs
  • 创建 dotnet new 项目模板 - .net core | microsoft docs
  • dotnet/dotnet-template-samples: samples showing how to create templates using the template engine for dotnet new and visual studio
  • dotnet new 命令 - .net core cli | microsoft docs

《使用.Net Core CLI命令dotnet new创建自定义模板.doc》

下载本文的Word格式文档,以方便收藏与打印。