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

VS Code保存后反引号被移除?Prettier格式化问题求助

解决Prettier自动移除对象键反引号的问题

你遇到的是Prettier的默认行为——它会自动移除对象键中不必要的引号(像Design这种单字、符合标识符规则的键,Prettier认为不需要反引号,所以会自动删掉)。要强制保留这些反引号,有两个可行方案:

方案一:修改Prettier配置,禁用自动移除不必要的引号

在项目的.prettierrc(或.prettierrc.json、prettier.config.js)配置文件中,添加quoteProps选项并设置为"preserve":

{
  "quoteProps": "preserve"
}

这个配置会让Prettier保留所有对象键的引号格式,不管是否必要。

方案二:用Prettier忽略注释单独保留指定代码块

如果不想全局修改配置,只想让特定的对象键保留反引号,可以在代码块前后添加/* prettier-ignore */注释:

/* prettier-ignore */
const categoryIcons = {
    'All Books': LocalLibraryIcon,
    'Business Management': AnalyticsIcon,
    'Biographies and Memoirs': PeopleIcon,
    `Design`: DesignServicesIcon,
    'Economics and Politics': AccountBalanceIcon,
    `Fiction`: AutoFixHighIcon,
    'Health and Fitness': MonitorHeartIcon,
    'Money and Investing': ShowChartIcon,
    'Non-Fiction': LibraryBooksIcon,
    `Psychology`: PsychologyIcon,
    `Poetry`: LocalFloristIcon,
    'Science and Nature': ScienceIcon,
    'Self-Improvement': TrendingUpIcon,
    `Technology`: CodeIcon,
};

这样Prettier就不会格式化这个对象,你的反引号就能保留下来了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 20:12:31