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

能否在VSCode中使用Task实现保存时自定义代码格式化?

用VSCode Task实现保存时自动运行forge fmt格式化Solidity代码

步骤1:创建格式化任务

  1. 打开VSCode,按下Ctrl+Shift+B(Windows/Linux)或Cmd+Shift+B(Mac),选择「创建tasks.json文件」,然后选择「Others」模板。
  2. 将生成的tasks.json内容替换为以下配置:
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Format Solidity with forge fmt",
      "type": "shell",
      "command": "forge fmt",
      "args": ["${file}"], // 仅格式化当前保存的文件,若要格式化所有Solidity文件可移除该参数
      "problemMatcher": [],
      "presentation": {
        "echo": false,
        "reveal": "never", // 不打开终端窗口,避免干扰
        "focus": false,
        "panel": "shared"
      }
    }
  ]
}

步骤2:配置保存时自动触发任务

打开VSCode的设置文件(settings.json),添加以下配置:

{
  "editor.formatOnSave": true,
  "[solidity]": {
    "editor.defaultFormatter": "", // 清空默认的Solidity格式化器
    "editor.formatOnSaveCommand": "Format Solidity with forge fmt" // 关联我们创建的任务
  }
}

验证功能

现在打开任意Solidity文件,修改后保存,VSCode会自动后台运行forge fmt格式化当前文件。如果forge命令不在系统PATH中,需要在tasks.json的command字段填写完整的forge路径(比如~/foundry/bin/forge fmt)。

内容的提问来源于stack exchange,提问作者Paul Razvan Berg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:40:17