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

是否存在可为TypeScript代码添加花括号的代码转换/格式化工具?

强制给控制语句、箭头函数添加花括号的工具方案

ESLint 快速实现

这是最省心的方案,ESLint有现成规则可以强制要求花括号,还支持自动修复:

  • 针对if/else、for/while等控制语句:启用curly规则并设为"all",强制所有控制结构必须用花括号包裹
  • 针对箭头函数:启用arrow-body-style规则并设为"always",自动把单行箭头函数转为带花括号和return的形式

示例配置

在项目的.eslintrc.json里添加:

{
  "rules": {
    "curly": ["error", "all"],
    "arrow-body-style": ["error", "always"]
  }
}

批量修复

运行以下命令自动修复整个仓库的代码:

eslint --fix .

自定义jscodeshift脚本(复杂场景适配)

如果ESLint的规则无法覆盖你特殊的代码场景,可以用jscodeshift写自定义转换脚本,精准处理所有需要加花括号的代码段。

箭头函数转换脚本示例

export default function transformer(file, api) {
  const j = api.jscodeshift;
  return j(file.source)
    // 找到所有箭头函数
    .find(j.ArrowFunctionExpression)
    // 过滤掉已经是块级语句的箭头函数
    .filter(path => path.node.body.type !== 'BlockStatement')
    // 替换为带花括号和return的形式
    .replaceWith(path => {
      const returnStmt = j.returnStatement(path.node.body);
      const blockBody = j.blockStatement([returnStmt]);
      return j.arrowFunctionExpression(
        path.node.params,
        blockBody,
        path.node.async
      );
    })
    .toSource();
}

运行脚本

jscodeshift -t ./your-transform-script.js ./src/

你可以基于这个脚本扩展,添加对if、循环语句的处理逻辑,实现全场景的花括号包裹。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 20:27:16