Search code examples
javascriptprettier

How to make Prettier to ignore a block of code?


Say we have a line of code:

const a = 'a'; const b = 'b';

and we wouldn't want it to be formatter by Prettier.

What I've tried so far:

1)

// prettier-ignore
const a = 'a'; const b = 'b';
// prettier-ignore-start
const a = 'a'; const b = 'b';
// prettier-ignore-end

In both cases it gets transformed into:

const a = 'a';
const b = 'b';

So how to ignore a block of code?


Solution

  • Sometimes multiple statements can be wrapped in a block with // prettier-ignore in front of it:

    // prettier-ignore
    {
    abcRouter('/api/abc', server);
    xRouter  ('/api/x', server);
    }
    

    Of course, that doesn't make sense for block-level const declarations, but you wrote that was not your actual code and just an example. So that's a solution that works in some but not in all cases. Overall, the strategy is to wrap multiple things in one thing that can be prettier-ignored.

    Another option is to move all the code you don't want to format (e.g., because it's generated) to a separate file excluded by .prettierignore.

    prettier-ignore-start and prettier-ignore-end are supported only in Markdown.