Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS Code auto formatting with prettier

Is it possible to auto format on VS Code in directory whose root doesn't have prettier config?

- root <-  current directory on VS Code
 - app
  - src <- Do i have to be here to run auto formatting??
   - .prettierrc
   - package.json
   - file1

I cannot run prettier in root directory. Do I have to be in the directory which has prettierrc?

like image 408
Pytan Avatar asked Jul 13 '20 04:07

Pytan


People also ask

Can you auto format in VS Code?

You can turn on the auto-formatting feature regardless of which programming language or code formatter you're using in VS Code. Most developers are using multiple code formatting extensions in VS Code, so you can ensure each of them automatically formats the file as you save it.

How do you format a pretty in VS Code?

The code formatting is available in Visual Studio Code through the following shortcuts: On Windows Shift + Alt + F. On Mac Shift + Option + F. On Linux Ctrl + Shift + I.


1 Answers

You need to include a proper .prettierrc file in the root directory, as the docs about Prettier Configuration File says:

The configuration file will be resolved starting from the location of the file being formatted, and searching up the file tree until a config file is (or isn’t) found.

Prettier intentionally doesn’t support any kind of global configuration. This is to make sure that when a project is copied to another computer, Prettier’s behavior stays the same. Otherwise, Prettier wouldn’t be able to guarantee that everybody in a team gets the same consistent results.

root
├── app
│   ├── file4
│   ├── public
│   │   └── file5
│   └── src
│       ├── file1
│       ├── package.json
│       └── .prettierrc
├── file2
├── file3
└── .prettierrc

If you have a directory structure like above, the files under root/app/src/ (file1, package.json and root/app/src/.prettierrc) will be formatted according to root/app/src/.prettierrc config file, and other files under root/ or its subdirectories (file2, file3, root/.prettierrc, file4, and file5) will be formatted according to root/.prettierrc config file.


Or you can configure default options of Prettier for VS Code:

Configuring Default Options

Some users may not wish to create a new Prettier config for every project or use the VS Code settings. Because Prettier searches recursively up the file path, you can place a global prettier config at ~/.prettierrc to be used as a fallback.

You can also use the setting prettier.configPath to provide a global configuration. However, be careful, if this is set this value will always be used and local configuration files will be ignored.

like image 168
Gorisanson Avatar answered Oct 10 '22 16:10

Gorisanson