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

如何阻止Prettier保存JavaScript文件时移除单引号?

问题:Prettier自动移除对象键的单引号,如何阻止?

我尝试保存以下Tailwind配置代码:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./src/**/*.{html,css,js,jsx,ts,tsx}'],
  theme: {
    extend: {},
    screens: {
      'sm': '640px',
      // => @media (min-width: 640px) { ... }

      'md': '768px',
      // => @media (min-width: 768px) { ... }

      'lg': '1024px',
      // => @media (min-width: 1024px) { ... }

      'xl': '1280px',
      // => @media (min-width: 1280px) { ... }

      '2xl': '1536px',
      // => @media (min-width: 1536px) { ... }
    },
  },
  plugins: [],
};

但保存文件时,Prettier会自动移除screens对象中sm、md、lg、xl、2xl这些键的单引号,我需要找到阻止这种行为的方法。

解决方案

要让Prettier保留对象键的单引号,直接修改Prettier配置文件即可,具体方式如下:

  • 使用独立配置文件(如.prettierrc.json)
    在配置文件中添加quoteProps项:
{
  "quoteProps": "preserve"
}
  • 在package.json中配置
    找到文件里的prettier字段,补充配置:
{
  "name": "你的项目名",
  "prettier": {
    "quoteProps": "preserve"
  }
}

quoteProps的三个可选值说明:

  • as-needed:默认行为,仅在键包含特殊字符时添加引号
  • consistent:统一给所有对象键加引号,或者都不加
  • preserve:完全保留代码原本的引号状态,不做任何修改

选择preserve就能让Prettier保留你给screens对象键添加的单引号,不会自动移除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:08:22