如何配置Prettier将Vue中的多行代码格式化为单行?
如何配置Prettier将多行Vue代码格式化为单行?
你需要调整Prettier的核心配置,让它判定这段代码无需换行,具体可通过修改.prettierrc文件实现:
关键配置说明
Prettier的自动换行逻辑主要由代码宽度阈值控制,核心调整以下两项:
- printWidth:设置代码允许的最大字符宽度,默认值为80,你的这段表达式长度超出了默认阈值才被拆分为多行。将其设为足够大的值(比如180或更高,可根据代码实际长度调整),让整个表达式能容纳在一行内。
- arrowParens:确保箭头函数即使只有单个参数也保留括号(设为
"always",该值为Prettier默认配置,确认即可避免因箭头函数格式触发换行)。
示例.prettierrc配置
{ "printWidth": 180, "arrowParens": "always", "semi": true, "singleQuote": false, "vueIndentScriptAndStyle": true }
效果验证
将你提供的多行代码:
Math.floor( (Math.max.apply( null, this.client.trailCourse.records.map((d) => d.sessionIndex) ) - 1) / 4 ) + 1;
放入Vue文件后,用Prettier格式化,即可得到你期望的单行格式:
Math.floor((Math.max.apply(null, this.client.trailCourse.records.map((d) => d.sessionIndex)) -1) /4) + 1;
内容的提问来源于stack exchange,提问作者Smile
相关产品推荐
相关产品推荐

