Skip to main content

Configure Prettier

Prettier is a code formatter that helps ensure consistent code style and formatting across your entire project. It can automatically format code in various languages, including JavaScript, HTML, CSS, and more. Frontend provides an integrated Prettier experience out of the box. Each time you create a new Frontend project, you will see a prompt like this:

Add and configure Prettier for opinionated code formatting?Yes❯ No

When you select "Yes," Frontend will automatically install prettier and @ongov/prettier-config-ontario-frontend as dependencies in your project and create prettier.config.js and .prettierignore file in the root of your project that includes the default configuration for Frontend projects.

You can run npm run format every time you want to run Prettier to format your project's codebase.

Add Prettier to an existing project

If you did not choose to install Prettier during the setup process, you can still add it to your project.

From your terminal, install the necessary Prettier dependencies:

# First install the necessary Prettier dependenciesnpm install --save-dev prettier @ongov/prettier-config-ontario-frontend

Once the packages have been installed, create a new file at the root of your project named prettier.config.js:

# Create a config file for Prettiertouch prettier.config.js

Then add the following content to prettier.config.js to extend the @ongov/prettier-config-ontario-frontend configuration:

module.exports = {    "extends": "@ongov/prettier-config-ontario-frontend"}

This tells Prettier to use the @ongov/prettier-config-ontario-frontend rules for your project.

Finally, add prettier --write as a script to package.json:

{  "scripts": {    "format": "prettier --write"  }}

You can now run npm run format from your terminal to format the files in your project.

Customize Prettier

The default configuration (@ongov/prettier-config-ontario-frontend) includes everything you need to format the standard files within an Frontend project. However, there may be times where you want to extend, override, or disable any default rules. If you need to do that, import the @ongov/prettier-config-ontario-frontend configuration into prettier.config.js and export the modifications:

module.exports = {  ...require('@ongov/prettier-config-ontario-frontend'),  printWidth: 120,};

Ignoring code

You can use .prettierignore to ignore certain files and folders completely.

Create a .prettierignore file in the root of your project. .prettierignore uses gitignore syntax.

# Ignore artifactsnode_modulesdist# Ignore vendor assetssrc/assets/vendor/*# Ignore .njk files*.njk