AI Workshop: learn to build apps with AI →
VS Code Tips: Prettier and Auto-Formatting

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Basic Setup

  1. Install the Prettier VS Code extension
  2. Enable Format on Save in VS Code settings
  3. Enable Format on Paste if you want pasted code to be formatted automatically

Add these settings to your settings.json:

{
  "editor.formatOnSave": true,
  "editor.formatOnPaste": true
}

Running Prettier on All Files

To format all files in a project at once:

  1. Create a .prettierrc file in your project root:
{
  "tabWidth": 2,
  "useTabs": false,
  "semi": false
}
  1. Run:
npx prettier -w .

Setting Up Prettier with ESLint for React

For React development, set up both ESLint and Prettier:

  1. Install the ESLint extension
  2. Install dependencies:
yarn add babel-eslint
yarn add eslint-config-airbnb
yarn add eslint-plugin-jsx-a11y
yarn add eslint-plugin-react
  1. Create .eslintrc.json in your project root:
{
  "parser": "babel-eslint",
  "extends": "airbnb",
  "plugins": ["react", "jsx-a11y", "import"]
}
  1. Install Prettier integration:
npm install -g prettier-eslint --save-dev
  1. Add to VS Code settings:
{
  "editor.formatOnSave": true,
  "javascript.format.enable": false,
  "prettier.eslintIntegration": true
}

Fixing HTML Formatting Issues

If Prettier is messing up your HTML formatting, you can use VS Code’s default HTML formatter instead:

{
  "[html]": {
    "editor.defaultFormatter": "vscode.html-language-features"
  }
}

Formatting Astro Files

Prettier doesn’t understand Astro syntax by default. To fix this:

  1. Install the Astro Prettier plugin:
npm install -D prettier-plugin-astro
  1. Make sure Editor: Format On Save and Editor: Format On Paste are enabled in VS Code settings

  2. Important: Make sure you open the specific project folder in VS Code, not a parent folder. Opening a parent folder may prevent the Astro formatter from working.

Lessons in this unit:

0: Introduction
1: Setup and Configuration Tips
2: Terminal Tips
3: Editing Tips
4: ▶︎ Prettier and Auto-Formatting
5: Language-Specific Settings
6: Emmet for Faster HTML/CSS
7: Debugging in VS Code
8: Fix node modules import errors in VS Code
9: Fixing TS issues in VS Code - Astro
10: Regex: select entire line starting with...