简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM