C# 创建模板项目

2022年7月21日 2006点热度 0人点赞 0条评论
内容纲要

目录结构:

└─templates
    └─consolesync
        └─content
            ├─.template.config
              ├──template.json
            └─AAA.Web.API

模板目录

1,随便创建一个空目录,然后在里面创建一个 ,在 templates 下创建模板目录,这个命令起名要可以随意。S 目录。
file

2,在 templates 下创建模板目录,这个命令起名要可以随意。这个就是模板存储的目录。
file

3,模板目录创建两个目录,分别是 contentlicenselicense 目录可以不要,content 目录用来存储解决方案、目录等。

创建项目和模板配置

4,创建解决方案或项目,按照平时的写法就行,注意,解决方案或者项目,请使用一个固定的统一前缀,如 AAA.Web,另外最好使用两部分组合,不要使用 AAA ,要使用 }.{ ,方便区配。
file

5,在 content 目录下,创建 .template.config 目录,然后在 .template.config 目录ixa创建 template.json 文件。
file

{
  "$schema": "http://json.schemastore.org/template",
  "author": "Me",
  "classifications": [ "Common", "Console" ],
  "identity": "ExampleTemplate.AsyncProject",
  "name": "Example templates: async project",
  "shortName": "aaaweb",
  "tags": {
    "language": "C#",
    "type": "project"
  },
  "sourceName": "AAA.Web",
  "preferNameDirectory": true 
}

其中, "sourceName": "AAA.Web" 是你模板中希望、可以被替换的变量,例如你设置了 AAA.Web,那么通过模板创建项目时, AAA.Web.sln 会被 替换 成新的名称。
file

参考 https://docs.microsoft.com/zh-cn/dotnet/core/tools/custom-templates

安装模板项目

6,然后在 templates 目录之上,执行:

 dotnet new -i .\templates\consolesync\

file

7,创建模板 dotnet new aaaweb -n ABC.Web,可以看到,AAA.Web 都被替换为 ABC.Web 了。
file
file

参考:https://docs.microsoft.com/zh-cn/dotnet/core/tutorials/cli-templates-create-item-template

打包模板项目和推送

需要依赖 nuget.exe,可以先下载:https://www.nuget.org/downloads
然后设置环境变量。

在 content 目录下,创建一个 .nuspec 文件,内容:

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>AAA.Web</id>
    <version>1.0.0</version>
    <description>
      我的模板
    </description>
    <authors>webmote</authors>
    <packageTypes>
      <packageType name="Template" />
    </packageTypes>
  </metadata>
</package>

file

然后执行命令:

 nuget pack .\content\.nuspec

会生成一个 .nupkg 包。
file

然后使用 dotnet nugetnuget 命令,推送 nupkg 包。 nuget.org 可以手动上传文件,私有仓库,一般只能用命令。

如果有 nupkg 文件,可以这样安装模板:

dotnet new -i xxx1.0.0.nupkg

如果是推送到仓库,可以上去查找拉取命令。本地要配置仓库源。
命令如:

dotnet new --install AAA.Web::1.0.0

这样就可以将模板拉取到本地了。

痴者工良

高级程序员劝退师

文章评论