Refactor the TSLint Configuration using 'extends'

christineoo avatar

Adding linters would help to make your project more robust as it might be able to catch programming errors, bugs, typos and etc. If you are using Typescript, you could use TSLint to lint your project. The full list of lint rules are available here. Besides that, you could also write custom lint rules for your own project needs.

Multiple tslint.json

A project can have multiple tslint.json configurations. For example, a tslint.json configuration for different environment mode.

In development mode 💻 , the rules below are needed.

{ "rules": { "no-any": true, "no-console": false, "no-debugger": false, "no-null-keyword": true, } }

In production mode 🚀 , the rules below are needed instead.

{ "rules": { "no-any": true, "no-console": true, "no-debugger": true, "no-null-keyword": true, } }

If you noticed, there are some duplicated rules in the tslint.*.json. We want the no-console and no-debugger rules to be enabled in development but disabled for production. On the other hand, the no-any and no-null-keyword rules are set to true and is being duplicated in each of the configuration files. We are all aware of the DRY principles ♻️ , so it would be nice if we could remove the duplicated rules!

'extends' field to the rescue

extends?: string | string[]

The extends field is an optional field in the tslint configuration that accepts a string or an array of strings. The value could be built-in configuration preset(eg: tslint:latest) or path to another configuration files which are extended by this configuration (refs).

So, let's see how we could refactor the tslint configuration file to utilize the extends field.

  1. Let's create a tslint.json configuration that contains all the required rules for development mode 💻


{ "rules": { "no-any": true, "no-console": false, "no-debugger": false, "no-null-keyword": true, } }
  1. Then, create a another tslint conguration for production use 🚀. Using the extends field, and give it a value of the path of the tslint configuration that you have created in step 1. You could add in additional rules that are needed specifically for production mode and/or override any rules that have been disabled.

{ "extends": "./tslint.json", "rules": { "no-console": true, "no-debugger": true, } }

You're all set~! 🎉 The no-any and no-null-keyword are no longer duplicated and now we have a cleaner tslint configuration file.

Hope you find this post useful and happy linting~ 🚓 👮