9

I have installed prettier via

yarn add prettier

I would like prettier to only format typescript code (I am developing AWS CDK project, there is no src folder by convention & there could be typescript files here and there). In other words, I would like prettier to check all files in my project that has extension *.ts.

I checked its documentation for configuration. But there is no such option to specify file extension.

How can I run prettier for only *ts files then? Is it even possible? If not, what could be the workaround?

user842225
  • 5,445
  • 15
  • 69
  • 119

2 Answers2

9

To exclude files from formatting, create a .prettierignore file at the root of your project.

And to format only the *.ts files you should ignore everything but the *.ts files.

Example

# Ignore everything recursively
*

# But not the .ts files
!*.ts

# Check subdirectories too
!*/

In the code above, the * means to ignore everything including the subfolders, and the next line !*.ts tells the prettier to reverse the previous ignoring of the .ts files. The last line !*/ means to check the subdirectories too, but with the previous rule, it's only looking for the .ts files.

Check the prettier and gitignore docs for more information.

Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
  • I did that in my .prettierignore. Now prettier ignore everything including *ts files. – user842225 Jan 14 '22 at 19:56
  • Same issue. It doesn't work. This is what I tried ```!**/*.ts !*.ts```. Also tried ```!*.ts``` – user842225 Jan 14 '22 at 20:00
  • Modify the ignore all with a forward slash like this `/*`. – alexanderdavide Jan 14 '22 at 20:04
  • 1
    Oh, it works now with your updated answer. But could you please clarify why now it works? I mean isn't `!*/` telling prettier not to ignore all files in subfolders no matter *.ts or not?? since there is no extension specified. I mean how can it guarantee it only checks typescript files in subfolder then? Why `!*/*.ts` doesn't work(I tried) but your answer works. – user842225 Jan 14 '22 at 20:08
  • Please check the updated answer. – Tamas Szoke Jan 14 '22 at 20:13
  • 1
    Thanks for the answer. I now understand why your answer works. But I still don't get why `!**/*.ts` doesn't work for subfolders when used as the 3rd line in your answer, do you happen to know the reason too? – user842225 Jan 14 '22 at 20:16
  • what if I want to format .ts files and .tsx how I can do that – Nagween Jaffer Nov 28 '22 at 08:54
7

For *.ts files:

npx prettier 'src/**/*.ts' --write

If you want target other file extensions:

npx prettier 'src/**/*.{js,ts,mjs,cjs,json}' --write
Tiago Bértolo
  • 3,874
  • 3
  • 35
  • 53