- Command Line Interface (CLI)
When using Prettier in the command line, you can specify the files to format using wildcards. For example:
bashprettier --write '**/*.{js,jsx,ts,tsx,css,md}'
This will format all .js, .jsx, .ts, .tsx, .css, and .md files in the project.
- 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.
- Using
.prettierignoreFile
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
- 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.
- 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.