VS Code中如何阻止Prettier转单引号为双引号且不修改配置?
解决Prettier与ESLint引号冲突的方案(无需修改配置文件)
方法一:调整VS Code保存时的动作顺序
在VS Code的**用户设置(settings.json)**中添加以下配置,让ESLint自动修复在Prettier格式化之后执行:
"editor.codeActionsOnSave": { "source.formatDocument": true, "source.fixAll.eslint": true }
保存代码时,Prettier会先完成格式化(将单引号转为双引号),紧接着ESLint会自动把双引号修正为符合规则的单引号,全程无需手动修改。
方法二:自定义宏命令控制执行顺序
如果方法一不生效,可以借助multi-command扩展实现更精准的顺序控制:
- 安装VS Code扩展multi-command
- 在用户
settings.json中配置宏:
"multiCommand.commands": [ { "command": "multiCommand.formatAndFix", "sequence": [ "editor.action.formatDocument", "eslint.executeAutofix" ] } ]
- 打开
keybindings.json,将保存快捷键绑定到这个宏:
{ "key": "ctrl+s", "command": "multiCommand.formatAndFix", "when": "editorTextFocus && !editorReadonly" }
之后按下保存键,就会先执行Prettier格式化,再执行ESLint自动修复。
方法三:行级/文件级忽略Prettier(按需使用)
如果只是个别字符串需要保留单引号,可以在目标行上方添加注释忽略Prettier的格式化:
// prettier-ignore const str = 'don\'t fix me';
如果需要忽略整个文件的Prettier格式化,在文件顶部添加:
/* prettier-ignore */
注意:此方法仅适合少量场景,大面积使用会丢失Prettier的其他格式化能力。
内容的提问来源于stack exchange,提问作者Ville
相关产品推荐
相关产品推荐

