How to Force Prettier to Always Put a Multilevel Ternary

Asked

Viewed 104 times

1

I am creating an application using Vscode as IDE and, to do the lint of the code, I’m using the Eslint and the GTS (Google Typescript Style) where in a code location I have something similar to that:

const sampleTernaryResult = 2 + 2 === 4 
  ? "it's not an even number"
  : "não é um numero impar";

In the Eslint file, I set it so that it always puts the ternary as multi-line, like this:

{
  "extends": "./node_modules/gts/",
  "rules": {
    "@typescript-eslint/no-explicit-any": 0,
    "max-len": ["warn", {"code": 160}],
    "multiline-ternary": ["error", "always"]
  }
}

When saving the file Eslint does the formatting for the multiline ternary. In doing so, Prettier detects that it is incorrect and if I save it again it returns the ternary to a single line. What do I need to do to make Prettier not make this fix? Is there a setting to make Prettier ignore this?

1 answer

3


You can be mixing things up. Prettier is a formatter extremely opinionated code, so it has very few configurations concerning the formatting of the code. More details.

This way, you have to choose which tool to use to format:

  • Prettier, in order to disable all Eslint formatting rules that may cause conflict - as is the case with multiline-ternary.
  • Do not use Prettier, leaving formatting to the style rules that Eslint provides.

It’s categorical: you can’t use Prettier and Eslint-specific formatting rules, otherwise you’ll find conflicts in various situations while developing your project.

Personally, I think it’s worth leaving the way Prettier does. For a long time, the Javascript community was very fragmented in terms of formatting. It still is, but with Prettier, that abyss has diminished, which is certainly very good.

Prettier provides a Eslint configuration to disable the style rules that most commonly cause conflicts. It’s called eslint-config-prettier.

Remember:

  • Primarily, the Eslint function is to do the lint of the code.
  • Prettier has the primary function of formatting the code.

Of course there may be some occasions when Prettier does something absurd. It is the case to use the magic commentary // prettier-ignore before an expression to prevent standard formatting.

  • 1

    I wanted to use Gts (Google Typescript Style) and he himself uses prettier. After all I reset my project and put the "standard-with-typescript" preset that solved my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.