乐闻世界logo
搜索文章和话题

How to use files with multiple extensions with Prettier?

1个答案

1
  1. Command Line Interface (CLI)

When using Prettier in the command line, you can specify the files to format using wildcards. For example:

bash
prettier --write '**/*.{js,jsx,ts,tsx,css,md}'

This will format all .js, .jsx, .ts, .tsx, .css, and .md files in the project.

  1. Prettier Configuration File

Create a .prettierrc file or add a prettier field in package.json; however, neither method directly supports specifying file extensions, as Prettier configuration files are primarily used for defining code style options.

  1. Using .prettierignore File

Create a .prettierignore file to exclude files and folders you don't want to format. This is not for directly specifying which file extensions to format, but for excluding files you don't want to format. For example:

plaintext
# Ignore node_modules folder node_modules # Ignore all HTML files *.html # Ignore specific CSS files ignore-this.css
  1. Using package.json Scripts

Set up a script in package.json to run Prettier and format files with specific extensions:

json
{ "scripts": { "format": "prettier --write '**/*.{js,jsx,ts,tsx,css,md}'" } }

Then, you can run npm run format or yarn format to format all files with the specified extensions.

  1. Editor Integration

Most modern code editors (such as Visual Studio Code) support Prettier plugins that automatically format files when saved. In the editor settings, you can typically specify which file types should be formatted on save.

For example, in Visual Studio Code, you can add the following configuration in settings.json:

json
"editor.formatOnSave": true, "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[javascriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[css]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[markdown]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, // ... other extensions

This way, when you save a file, Prettier will automatically format files with supported extensions.

2024年6月29日 12:07 回复

你的答案