You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET自定义模板无法替换sourceName小写形式的文件及文件夹名

.NET自定义模板实现小写名称替换方案

问题背景

我有一个可生成完整解决方案的自定义.NET模板,其JSON配置如下:

{
    "$schema": "http://json.schemastore.org/InsertNameHere",
    "author": "MiTek Nucleus Team",
    "classifications": [ "ASP.NET", "Nucleus API", "Solution" ],
    "identity": "Nucleus.InsertNameHeres.AspNetCore.WebAPI",
    "name": "MiTek Nucleus Service",
    "sourceName": "InsertNameHere",
    "preferNameDirectory": true,
    "placeholderFilename": "-.-",
    "shortName": "nucleus-service",
    "tags": {
        "language": "C#",
        "type": "solution"
    },
    "sources": [
        {
            "modifiers": [
                {
                    "exclude":[
                        "**/[Bb]in/**",
                        "**/[Oo]bj/**",
                        "**/.git/**",
                        "**/.vscode/**",
                        "**/.vs/**",
                        ".InsertNameHere.config/**/*",
                        "**/*.filelist",
                        "**/*.user",
                        "**/*.lock.json"
                    ],
                    "rename": {
                        "editorconfig": ".editorconfig",
                        "gitignore": ".gitignore",
                        "npmrc": ".npmrc",
                        "gitkeep": ".gitkeep",
                        "helmignore": ".helmignore"
                    }
                }
            ]
        }
    ]
}

原本预期执行dotnet new <template> -n <some_name>命令后,模板中名为insertnamehere的文件夹和insertnamehere-api.module.ts的TypeScript文件会被替换为指定解决方案名称的小写形式,但实际并未生效,需要实现该替换功能。

解决方案

1. 添加自定义符号生成小写名称

在模板JSON中新增symbols节点,定义一个自动生成小写名称的变量,用来匹配并替换模板中的全小写占位符:

"symbols": {
    "lowerCaseName": {
        "type": "generated",
        "generator": "casing",
        "parameters": {
            "source": "sourceName",
            "toLower": true
        },
        "replaces": "insertnamehere"
    }
}

这个配置会将sourceName(即通过-n指定的名称)自动转换为全小写,然后替换模板中所有insertnamehere的实例,包括文件夹名和文件名。

2. 确保模板文件/文件夹命名匹配占位符

模板中的目标文件夹必须严格命名为insertnamehere(全小写),目标文件必须命名为insertnamehere-api.module.ts,这样才能被lowerCaseName的替换规则正确匹配。

3. 检查modifiers配置

确认sources下的modifiers中的exclude列表没有过滤掉需要替换的文件或文件夹,当前配置的排除规则不会影响小写替换操作,无需修改。

验证命令

执行模板生成命令时,指定目标名称即可触发替换:

dotnet new nucleus-service -n MyNewService

此时模板中的insertnamehere文件夹会被替换为mynewservice,insertnamehere-api.module.ts会被替换为mynewservice-api.module.ts。

内容的提问来源于stack exchange,提问作者Logan K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 08:38:12