Prettier

Prettier is an opinionated code formatter that automatically formats your code to ensure consistent style throughout your project. It helps in maintaining code readability and uniformity across your extension codebase.

Extension.js offers first-class support for Prettier, allowing you to easily integrate it into your extension development workflow.

Starter Prettier Template

Extension.js includes a New Tab Prettier template, providing an out-of-the-box configuration to automatically format your JavaScript, TypeScript, and JSX code.

Prettier Extension Template

Try it yourself

npm
pnpm
yarn
npx extension@latest create my-extension --template=new-prettier

Usage With An Existing Extension

To use Prettier in your existing Extension.js project, you need to install the necessary dependencies and configure Prettier.

Installation

Install Prettier as a development dependency:

npm
pnpm
yarn
npx install -D prettier

Prettier Configuration

Create a Prettier configuration file (.prettierrc.json) at the root of your project to customize the formatting rules. Here's an example configuration:

{
  "semi": true,
  "singleQuote": true,
  "trailingComma": "es5",
  "printWidth": 80,
  "tabWidth": 2
}

Example Usage in a JavaScript File

Once Prettier is configured, it will automatically format your JavaScript files based on the rules defined in .prettierrc.json. Here’s an example of how Prettier formats code:

function sayHello() {
    console.log("Hello, Extension.js")
}

+ After Prettier runs:
function sayHello() {
  console.log('Hello, Extension.js');
}

Example Usage in a TypeScript File

Prettier also works with TypeScript files to ensure consistent formatting. Here’s an example TypeScript file before and after Prettier formatting:

Before Prettier:
interface Props { name:string;age:number}

function sayHello({name, age}:Props) {return `${name} is ${age} years old`}

After Prettier:
interface Props {
  name: string;
  age: number;
}

function sayHello({ name, age }: Props) {
  return `${name} is ${age} years old`;
}

Running Prettier

To manually run Prettier on your project, use the following command:

npm
pnpm
yarn
prettier --write .

This will format all files in your project according to your .prettierrc.json configuration.

Integration with ESLint

Prettier can be integrated with ESLint to automatically fix formatting issues as part of the linting process. To do this, install the required plugins:

npm
pnpm
yarn
npx install -D eslint-config-prettier eslint-plugin-prettier

Then, update your ESLint configuration to use Prettier:

{
  "extends": ["eslint:recommended", "plugin:react/recommended", "prettier"],
  "plugins": ["react", "prettier"],
  "rules": {
    "prettier/prettier": "error"
  }
}

Now, ESLint will report and automatically fix formatting issues based on Prettier’s rules.

Next Steps

  • Learn how to integrate ESLint with your extension.
  • Ensure consistent code formatting across your extension with Prettier.