Search code examples
visual-studio-codeeslintprettier

In VSCode, why is Prettier formatting my code and then highlighting it as an error?


This is confusing because I have one project set up with a .eslintrc.js that formats everything fine, but I can't get it to work on another project that is a very similar setup. Here is that file:

I have Prettier set as the formatter, and VSCode set to format on save. But when it formats, it seems to use the rules from the Prettier settings page in VSCode, and not from the eslintrc file. The result is that it formats the code in one way and then throws a linting error because the way it formatted is not following the rules. I know it's gotta be something stupid but I can't figure out how to make it use the ESLint settings to format.

enter image description here

This is eslintrc.js

module.exports = {
  env: {
    browser: true,
    es6: true,
    node: true
  },
  extends: [
    "prettier",
    "eslint:recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:react/recommended"
  ],
  globals: {
    Atomics: "readonly",
    SharedArrayBuffer: "readonly"
  },
  parser: "@typescript-eslint/parser",
  parserOptions: {
    ecmaFeatures: {
      jsx: true
    },
    ecmaVersion: 2018,
    sourceType: "module"
  },
  plugins: ["@typescript-eslint", "prettier"],
  settings: {
    "import/parsers": {
      "@typescript-eslint/parser": [".ts", ".tsx"]
    },
    "import/resolver": {
      typescript: {}
    }
  },
  rules: {
    "prettier/prettier": ["error"],
    "react/jsx-uses-react": 1,
    "max-len": [2, { code: 80, comments: 120, tabWidth: 2 }],
    "@typescript-eslint/interface-name-prefix": 0,
    "@typescript-eslint/no-unused-vars": 0
  }
};

Solution

  • Ah okay so the answer here was to implement the right Prettier rules in .prettierrc.

    The VSCode Prettier settings can be set specifically for the workspace, which was what caused me confusion (I had trailingComma set to none in another workspace which made me confused about why that workspace was correctly formatting things).

    I added this code to .prettierrc, which makes the Prettier formatter consistent with the ESLint rules:

    {
      "arrowParens": "avoid",
      "trailingComma": "none",
      "tabWidth": 2,
      "semi": true,
      "singleQuote": false
    }
    

    I (mistakenly?) thought that Prettier automatically derived its formatting options from the ESLint rules.