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

如何配置Visual Studio Code使嵌套条件格式化为同一缩进层级?

如何让VS Code格式化后保持嵌套三元表达式同一缩进列?

你有一段嵌套三元表达式的JavaScript代码:

const folder = cookieSorted.branded.includes(cookie.name) ? "Branded" :
    cookieSorted.christmas.includes(cookie.name) ? "Christmas" :
    cookieSorted.danishButter.includes(cookie.name) ? "Butter" :
    cookieSorted.holloween.includes(cookie.name) ? "Halloween" : "Other";

但VS Code自动格式化后,会把嵌套的分支逐行缩进,变成这样:

const folder = cookieSorted.branded.includes(cookie.name) ? "Branded" :
    cookieSorted.christmas.includes(cookie.name) ? "Christmas" :
        cookieSorted.danishButter.includes(cookie.name) ? "Butter" :
            cookieSorted.holloween.includes(cookie.name) ? "Halloween" : "Other";

以下是两种常用格式化工具的解决方法:

一、使用Prettier格式化工具

在项目根目录创建.prettierrc配置文件,添加如下配置:

{
  "indentChains": false
}

这个配置会关闭链式表达式的自动缩进,让所有三元分支保持同一缩进级别。如果只是临时不想格式化某段代码,可以在代码上方添加注释// prettier-ignore,Prettier就会跳过这段代码的格式化。

二、使用VS Code内置的JS/TS格式化工具

  1. 打开VS Code设置(快捷键:Windows/Linux用Ctrl+,,Mac用Cmd+,)
  2. 搜索Editor: Default Formatter,确认当前使用的是vscode.typescript-language-features
  3. 搜索并找到JavaScript > Format > Indent Chains选项,取消勾选;如果是TypeScript代码,找到TypeScript > Format > Indent Chains取消勾选
    或者直接在settings.json中添加配置:
"javascript.format.options": {
  "indentChains": false
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 02:58:23