使用更漂亮的 VS Code 自动格式化

VS Code auto formatting with prettier

是否可以在根目录没有更漂亮配置的目录中自动格式化 VS 代码?

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

我不能 运行 在根目录中更漂亮。我必须在有 prettierrc 的目录中吗?

您需要在根目录中包含一个适当的 .prettierrc 文件,如 docs about Prettier Configuration File 所说:

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

如果您的目录结构如上,root/app/src/file1package.jsonroot/app/src/.prettierrc)下的文件将根据[=15=进行格式化]配置文件,以及root/或其子目录(file2file3root/.prettierrcfile4file5)下的其他文件根据 root/.prettierrc 配置文件格式化。


或者你可以 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.