Prettier

Making my code look pretty.

August 28, 2024 ā€¢ Code

Prettier is an opinionated code formatter that enforces a consistent style by parsing your code and re-printing it with its own rules. When using the Prettier extension in Visual Studio Code (VSCode), it integrates seamlessly with the editor to format your code automatically based on the settings you provide.

How Prettier Works with VSCode

  1. Installation
  2. : You need to install the Prettier extension from the VSCode marketplace.
  3. Configuration
  4. : Prettier can be configured using aĀ 
  5. .prettierrc
  6. Ā file,Ā 
  7. prettier.config.js
  8. , or directly in theĀ 
  9. settings.json
  10. Ā file of VSCode.
  11. Formatting
  12. : Prettier formats your code based on the configuration whenever you save a file or manually trigger the formatting command.

Configuring Prettier for Different Projects

To achieve different Prettier settings for different projects, you can use the following approach:

  1. Global Settings
  2. : Configure the default settings in your global VSCode settings (
  3. settings.json
  4. ).
  5. Project-Specific Settings
  6. : Override the global settings with project-specific settings using aĀ 
  7. .prettierrc
  8. Ā file orĀ 
  9. prettier.config.js
  10. Ā in the project directory.
  11. Disable Prettier for Specific Projects
  12. : Use theĀ 
  13. prettier.disableLanguages
  14. Ā setting in the project'sĀ 
  15. settings.json
  16. Ā to disable Prettier for specific file types.

Step-by-Step Configuration

1. Global Settings

Set the global Prettier settings in your VSCodeĀ settings.json:

{
	"editor.formatOnSave":Ā true,
	"prettier.tabWidth":Ā 4,
	"prettier.useTabs":Ā false
}

2. Project-Specific Settings

Create aĀ .prettierrcĀ file in the root of the project where you want custom settings:

{
	"tabWidth":Ā 2,
	"useTabs":Ā false
}

Or useĀ prettier.config.js:

module.exportsĀ =Ā {
	tabWidth:Ā 2,
	useTabs:Ā false
};

3. Disable Prettier for Specific Projects

In the project where you want to disable Prettier, create or update theĀ .vscode/settings.jsonĀ file:

{
	"editor.formatOnSave":Ā false,
	"prettier.disableLanguages":Ā ["javascript",Ā "typescript",Ā "json"]
}

Example Directory Structure

project-root/
	.prettierrc
	.vscode/
		settings.json
	src/

Summary

  • Global Settings
  • : Configure inĀ 
  • settings.json
  • Ā for default behavior.
  • Project-Specific Settings
  • : UseĀ 
  • .prettierrc
  • Ā orĀ 
  • prettier.config.js
  • Ā in the project directory.
  • Disable Prettier
  • : UseĀ 
  • .vscode/settings.json
  • Ā in the project directory to disable Prettier for specific file types.

By following these steps, you can manage Prettier settings effectively across different projects in your workspace.

Invely's