Prettier doesn't format .tsx file

Viewed 31812

I've used the Prettier extension in the visual studio code editor for a long time, but recently I am writing to React with Typescript. So I need to configure for Prettier to format .tsx files.

7 Answers

Edit setting with following in settings.json of VScode

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

Expanding on iNeelPatel's answer, I had to add two lines to VSCode JSON settings:

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

An easy UI alternative to what has been proposed already:

  1. Search for "default formatter" in your vscode settings.
  2. Click on "Text Editor" and set the default formatter to "Prettier - Code formatter".
  3. Enjoy.

Create a .vscode folder at the root of your project. In the .vscode folder, create the settings.json file, and in it, write this section:

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

Don't forget to add .vscode in the .gitignore file.

My Usage

The way I set this up is to use eslint's .eslintrc.json file. First of all, in the "extends" array, I've added

"plugin:@typescript-eslint/recommended"

and

"prettier/@typescript-eslint"

Then, I've set "parser" to "prettier/@typescript-eslint"

Finally, in "plugins" array I've added "@typescript-eslint".

You'll need to grab a couple of NPM packages (install with the -D option):

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

For reference, my entire .eslintrc.json file:

{
  "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"
  }
}

Hope this helps.

Perhaps helpful to someone - if with all the above, still no luck, you may want to restart VSCode or from command palette (⌘CMD + ⇧Shift + P) and fire up "Restart ESLint Server" - that shd do, then :)

Related