【问题标题】:Prettier doesn't format .tsx filePrettier 不格式化 .tsx 文件
【发布时间】:2020-08-27 02:31:42
【问题描述】:

我在 Visual Studio 代码编辑器中使用 Prettier 扩展已经很长时间了,但最近我正在用 Typescript 写 React。所以我需要配置 Prettier 来格式化 .tsx 文件。

【问题讨论】:

  • 你有prettier作为这个项目的依赖吗?

标签: reactjs typescript visual-studio-code prettier tsx


【解决方案1】:

在 VScode 的 settings.json 中编辑设置

"[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
},

【讨论】:

  • 你让我开心!
  • 如果您想知道如何访问 settings.json -> stackoverflow.com/a/65909052/5888998
  • 要打开设置,请按以下步骤操作:Shift + CMD + P,输入“设置”,点击“首选项:打开设置(JSON)”
  • 谢谢!!!!!!
【解决方案2】:

扩展 iNeelPatel 的回答,我不得不在 VSCode JSON 设置中添加两行:

"[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
"[typescriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }

【讨论】:

    【解决方案3】:

    这将给出完美的解决方案

    “我刚才也发生了同样的事情。我在设置中将 prettier 设置为默认格式化程序,它又开始工作了。我的默认格式化程序为空。”

    https://github.com/microsoft/vscode/issues/108447#issuecomment-706642248

    【讨论】:

      【解决方案4】:

      我的使用情况

      我设置的方式是使用 eslint 的 .eslintrc.json 文件。首先,在"extends"数组中,我添加了

      "plugin:@typescript-eslint/recommended"
      

      "prettier/@typescript-eslint"
      

      然后,我将"parser" 设置为"prettier/@typescript-eslint"

      最后,我在"plugins" 数组中添加了"@typescript-eslint"

      您需要获取几个 NPM 包(使用 -D 选项安装):

      @typescript-eslint/eslint-plugin
      @typescript-eslint/parser
      

      作为参考,我的整个.eslintrc.json 文件:

      {
        "env": {
          "browser": true,
          "es6": true,
          "jest": true
        },
        "extends": [
          "plugin:@typescript-eslint/recommended",
          "prettier/@typescript-eslint",
          "plugin:prettier/recommended"
        ],
        "globals": {
          "Atomics": "readonly",
          "SharedArrayBuffer": "readonly"
        },
        "parser": "@typescript-eslint/parser",
        "parserOptions": {
          "ecmaFeatures": {
            "jsx": true
          },
          "project": "./src/tsconfig.json",
          "ecmaVersion": 2018,
          "sourceType": "module"
        },
        "plugins": ["react", "@typescript-eslint", "jest"],
        "rules": {
          "react/react-in-jsx-scope": "off"
        }
      }
      

      希望这会有所帮助。

      【讨论】:

        【解决方案5】:

        一个简单的 UI 替代方案:

        1. 在您的 vscode 设置中搜索“默认格式化程序”。
        2. 点击“文本编辑器”并将默认格式化程序设置为“Prettier - 代码格式化程序”。
        3. 享受吧。

        【讨论】:

          猜你喜欢
          • 2021-03-17
          • 2022-06-24
          • 2020-01-14
          • 1970-01-01
          • 2021-09-12
          • 2018-10-20
          • 1970-01-01
          • 2019-08-27
          • 2020-10-17
          相关资源
          最近更新 更多