TypeScript: Adding Linting to an AWS CDK Project

AWS CDK TypeScript Linting ESLint

2 min read | by Jordi Prats

When building a robust infrastructure using AWS CDK in TypeScript, maintaining clean, consistent, and error-free code is critical. One way to ensure your codebase stays maintainable is by incorporating a linter, such as ESLint. Linting helps catch syntax issues, enforce coding standards, and maintain overall code quality throughout your project.

Let's assume you have a CDK project you want to add linting to. First we'll have to install ESLint:

npm install eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-cdk typescript-eslint --save-dev

Next, create the eslint.config.js file in the root of your project where we'll be able to define the linting rules and configuration. To get started we can use the following example, but to use additional plugins we'll have to update this file:

const eslint = require('@eslint/js');
const tseslint = require('typescript-eslint');
const cdk = require('eslint-plugin-cdk');

module.exports =  tseslint.config(
  eslint.configs.recommended,
  ...tseslint.configs.recommendedTypeChecked,
  {
    languageOptions: {
      parserOptions: {
        project: true,
      },
    },
  },
  {
    files: ["**/*.ts", "**/*.tsx"],
  },
  {
      ignores: [
          "node_modules",
          "dist",
          "**/dist",
          "coverage",
          "eslint.config.js",
          "cdk.out",
          "cdk.context.json",
          "jest.config.js",
          "index.js",
      ]
  }
);

Next, we can add the commands in the scripts section of the package.json file:

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

Once the configuration is in place, you can run the linting command to check for any issues in your codebase:

$ npm run lint

> lint
> eslint .


/Users/jordiprats/git/demo-infra/src/bin/main.ts
  8:5  error  'region' is never reassigned. Use 'const' instead  prefer-const

 1 problem (1 error, 0 warnings)
  1 error and 0 warnings potentially fixable with the `--fix` option.

Some of the issues can be fixed automatically by running the lint:fix command:

$ npm run lint:fix

> lint:fix
> eslint . --fix

Posted on 11/09/2024

Categories