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

使用swagger-codegen CLI加载本地Mustache模板报错,求解决方案

问题:使用本地Mustache模板运行swagger-codegen CLI报错

我已将typescript-fetch模板下载到项目的.\template目录,想基于该模板做自定义调整,原以为只需在CLI命令中传入--template-dir .\template参数即可运行,命令如下:

Java -jar .\bin\swagger-codegen-cli.jar generate -l typescript-fetch -i https://localhost:7113/swagger/v1/swagger.json -o output -Dio.swagger.v3.parser.util.RemoteUrl.trustAll=true --template-dir .\template

但运行后抛出异常:

07:55:44.212 [Thread-1] INFO  i.s.codegen.v3.AbstractGenerator - writing file c:\projects\trustwell-api-client-ts\output\index.ts
Exception in thread "Thread-1" java.lang.RuntimeException: Could not generate supporting file 'SupportingFile:
        templateFile: api.mustache
        folder:
        destinationFilename: api.ts
'
        at io.swagger.codegen.v3.DefaultGenerator.generateSupportingFiles(DefaultGenerator.java:666)
        at io.swagger.codegen.v3.DefaultGenerator.generate(DefaultGenerator.java:789)
        at io.swagger.codegen.v3.cli.cmd.Generate.run(Generate.java:388)
        at java.lang.Thread.run(Unknown Source)
Caused by: com.github.jknack.handlebars.HandlebarsException: c:\projects\trustwell-api-client-ts\.\template\api.mustache:142:73: found: '-last', expected: 'no viable alternative at input '{{^-last''
                                        ? configuration.accessToken("{{name}}", [{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}])
                                                                         ^
        at com.github.jknack.handlebars.internal.HbsErrorReporter.syntaxError(HbsErrorReporter.java:93)
        at com.github.jknack.handlebars.internal.antlr.ProxyErrorListener.syntaxError(ProxyErrorListener.java:41)
        at com.github.jknack.handlebars.internal.antlr.Parser.notifyErrorListeners(Parser.java:544)
...

CLI已识别到本地模板文件夹,但无法正常生成文件,请问如何正确使用本地Mustache模板运行swagger-codegen CLI?


解决方法

从报错信息来看,问题根源是api.mustache模板中的Handlebars语法不符合当前swagger-codegen CLI版本的解析规则,具体处理步骤如下:

  • 匹配模板与CLI版本
    你下载的typescript-fetch模板版本可能和CLI版本不兼容。先运行以下命令查看CLI版本:

    java -jar .\bin\swagger-codegen-cli.jar version
    

    然后从swagger-codegen对应版本的仓库分支中下载匹配的typescript-fetch模板,替换本地.\template目录下的文件。

  • 修正模板语法
    若要保留当前模板,需修改api.mustache中的错误语法:将非标准的{{^-last}}/{{/-last}}替换为Handlebars标准的{{#unless @last}}/{{/unless}},修改后的代码片段如下:

    ? configuration.accessToken("{{name}}", [{{#scopes}}"{{{scope}}}"{{#unless @last}}, {{/unless}}{{/scopes}}])
    

    保存修改后重新运行生成命令。

  • 确认模板目录结构
    确保本地.\template目录的结构与官方typescript-fetch模板完全一致,所有必要的模板文件(如model.mustache、index.mustache等)都在正确路径下,避免因文件缺失或路径错误导致生成失败。


内容的提问来源于stack exchange,提问作者THX-1138

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 23:27:28