TypeScript: Adding Prettier to an AWS CDK Project

AWS CDK TypeScript prettier

3 min read | by Jordi Prats

Maintaining clean and consistent code is crucial for every project, and tools like prettier can help make it effortless. Prettier is a code formatter that supports a wide variety of languages, including TypeScript. By integrating it into your project's workflows, you can ensure that your code stays consistently formatted, enhancing readability and reducing code review friction.

For this example we are going to use a CDK project written in TypeScript, but the steps are the same for any TypeScript project.

Installing prettier

We can install prettier as a development dependency in your project by running the following command:

npm install prettier --save-dev

Configuring prettier

We can (optionally) configure prettier by creating a .prettierrc file in the root of your project. This file will contain the configuration options for Prettier. Here is an example configuration file:

{
  "semi": false,
  "singleQuote": true,
  "trailingComma": "all",
  "tabWidth": 2
}

The options we are using in the example are:

  • semi: Ensures that semicolons are added at the end of statements.
  • singleQuote: If set to true, enforces the use of single quotes instead of double quotes.
  • trailingComma: Adds a trailing comma wherever possible. This is helpful for clean diffs in version control.
  • tabWidth: Sets the number of spaces per indentation.

We can also just use the default configuration by not creating the .prettierrc file.

The other file that we can use is .prettierignore to ignore files or directories that we don't want Prettier to format. Here is an example of a .prettierignore file:

dist
node_modules

Running prettier

We can run prettier by adding it to the scripts section of the package.json file:

{
(...)
  "scripts": {
    "cdk": "node cdk-wrapper.js",
    "ts-node": "ts-node",
    "lint": "eslint .",
    "lint:fix": "eslint . --fix",
    "prettier": "prettier --check .",
    "prettier:fix": "prettier --write ."
  }
}

With these commands in place, we can now run prettier to check the formatting of our files:

$ npm run prettier

> prettier
> prettier --check .

Checking formatting...
[warn] .github/workflows/deploy-eks.yml
[warn] Code style issues found in the above file. Run Prettier with --write to fix.

If we want to automatically fix the formatting issues, we can run npm run prettier:fix:

$ npm run prettier:fix

> prettier:fix
> prettier --write .

.github/workflows/lint.yaml 4ms (unchanged)
.github/workflows/minify.yml 3ms
bin/main.ts 48ms (unchanged)
cdk.json 0ms (unchanged)
eslint.config.js 5ms (unchanged)
package-lock.json 32ms (unchanged)
package.json 1ms (unchanged)
README.md 21ms (unchanged)
tsconfig.json 1ms (unchanged)

Posted on 17/09/2024

Categories