創建自定義項目模板

創建一個集成了所有自己常用組件的項目模板,能夠在新項目啟動時節省大量的時間。.net對自建項目模板支援還是比較友好的,但問題是文檔不多,我查到的文檔裡面較少比較詳細的就只有這篇部落格。接下來,我會按照步驟重新創建一個模板來解釋模板文件的配置。

  1. 創建一個控制台項目(也可以是其他類型的項目)

    dotnet new console -n TestTemplate
    
  2. 在項目根目錄下創建 .template.config 目錄,並在該目錄下創建 template.json 文件

     {
         "$schema": "//json.schemastore.org/template",
         "author": "Venyo Wong",
         "classifications": [ "Web", "MVC" ],
         "identity": "Base",
         "name": "Base",
         "shortName": "base",
         "preferNameDirectory": true,
         "symbols": {
             "name": {
                 "type": "parameter",
                 "replaces": "TestTemplate",
                 "FileRename": "TestTemplate",
                 "isRequired": true
             }
         }
     }
    

    這樣就創建好了一個最基礎的項目模板。

    • classifications 欄位代表該模板的類型,會在 dotnet new 的模板列表體現出來
    • identity、name、shortName 是用來識別模板的欄位
    • preferNameDirectory 該欄位表示是否將目錄名稱作為項目名稱,比如該欄位設置為 true,在一個名為 Test 的目錄下創建項目,在未指定項目名稱的前提下,項目名稱默認為 Test
    • symbols 代表創建項目時可以指定的參數
    • symbols.name 表示使用此模板創建項目時可以指定 name 參數
    • symbols.name.replaces: “TestTemplate” 表示在創建項目時,需要把文件中的 TestTemplate 字元串替換為用戶傳入的 name 參數
    • symbols.name.FileRename: “TestTemplate” 表示在創建項目時,需要把文件名中的 TestTemplate 字元串替換為用戶傳入的 name 參數
  3. 修改項目內容,此處僅在 Program.cs 文件中加入 TestTemplate,用於測試效果

     // See //aka.ms/new-console-template for more information
     Console.WriteLine("TestTemplate");
    
  4. 安裝本地項目模板

     >dotnet new --install.
    
     將安裝以下模板包:
     D:\code\test\TestTemplate
    
     成功: D:\code\test\TestTemplate 已安裝以下模板:
     模板名   短名稱   語言  標記
     ----  ----  --  -------
     Base  base      Web/MVC
    
  5. 使用自定義模板創建項目

     >dotnet new base -n TestProject
    
     已成功創建模板「Base」。
    

    打開 TestProject 項目可以看到項目配置文件名變更為 TestProject.csproj,Program.cs 文件內容變更為

     // See //aka.ms/new-console-template for more information
     Console.WriteLine("TestProject");
    
  6. 排除部分文件、目錄,在項目模板開發過程中,難免會自動生成一些文件,比如 .vs、.vscode 等,想要將這些文件、目錄排除在模板之外,需要做額外的配置。

     {
         "$schema": "//json.schemastore.org/template",
         "author": "Venyo Wong",
         "classifications": [ "Web", "MVC" ],
         "identity": "Base",
         "name": "Base",
         "shortName": "base",
         "preferNameDirectory": true,
         "symbols": {
             "name": {
                 "type": "parameter",
                 "replaces": "TestTemplate",
                 "FileRename": "TestTemplate",
                 "isRequired": true
             }
         },
         "sources": [
             {
                 "modifiers": [
                     {
                         "exclude": [
                             ".template.config/**",
                             ".vs/**",
                             ".vscode/**",
                             "bin/**",
                             "log/**",
                             "obj/**",
                             "ProjectTemplate.xml"
                         ]
                     }
                 ]
             }
         ]
     }
    
  7. 添加可選模組,此處以 Newtonsoft.Json 為例進行說明。

    項目配置引用 Newtonsoft.Json 包。

     <ItemGroup Condition="$(json)">
         <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
     </ItemGroup>
    

    在項目根目錄添加 Json 目錄,並且添加 JsonHelper.cs 文件,內容如下:

     using Newtonsoft.Json;
    
     namespace TestTemplate.Json;
    
     public static class JsonHelper
     {
         public static (string, Exception?) ToJson(this object obj)
         {
             if (obj == null)
             {
                 return default;
             }
    
             try
             {
                 return (JsonConvert.SerializeObject(obj), null);
             }
             catch (Exception ex)
             {
                 return (string.Empty, ex);
             }
         }
     }
    

    Program.cs 文件修改為:

     // See //aka.ms/new-console-template for more information
     #if (!json)
     Console.WriteLine("TestTemplate");
     #else
     using TestTemplate.Json;
    
     Console.WriteLine(JsonHelper.ToJson(new { Key = "Value" }));
     #endif
    

    最後修改 template.json 配置如下:

     {
         "$schema": "//json.schemastore.org/template",
         "author": "Venyo Wong",
         "classifications": [ "Web", "MVC" ],
         "identity": "Base",
         "name": "Base",
         "shortName": "base",
         "preferNameDirectory": true,
         "symbols": {
             "name": {
                 "type": "parameter",
                 "replaces": "TestTemplate",
                 "FileRename": "TestTemplate",
                 "isRequired": true
             },
             "json": {
                 "type": "parameter", 
                 "dataType":"bool", 
                 "defaultValue": "true"
             }
         },
         "sources": [
             {
                 "modifiers": [
                     {
                         "exclude": [
                             ".template.config/**/*",
                             ".vs/**",
                             ".vscode/**",
                             "bin/**",
                             "log/**",
                             "obj/**",
                             "ProjectTemplate.xml"
                         ]
                     },
                     {
                         "condition": "(!json)",
                         "exclude": [
                             "Json/**"
                         ]
                     }
                 ]
             }
         ]
     }
    
  8. 生成帶有 json 模組的項目

     dotnet new base -n TestProject
    
     生成項目結構如下:
     TestProject
     │  Program.cs
     │  TestProject.csproj
     │
     └─Json
             JsonHelper.cs
    
  9. 生成不帶有 json 模組的項目

    dotnet new base -n TestProject --json false
    
    生成項目結構如下:
    TestProject
        Program.cs
        TestProject.csproj
    
    沒有子文件夾
    

以上為我自己常用的模板配置,其他還有一些可配置項,感興趣的讀者可以查閱官方文檔或者查看官方demo。歡迎聯繫討論:[email protected]