Prettier & TSLint

Let Prettier take care of code formatting, and TSLint of the rest

Install

It can be used globally but is much better to have it in the project. Run

$ npm i --save-dev prettier tslint tslint-config-prettier tslint-plugin-prettier tslint-react
  • tslint-plugin-prettier: reports the errors visually. // TODO: check what really does

  • tslint-config-prettier: disables all conflicting rules that may cause such problems.

  • tslint-react: adds some extra configuration for react projects.

Configuration

Once all the dependencies has been installed, we will need to create a tslint.json

{
    "defaultSeverity": "warning",
    "extends": ["tslint:latest", "tslint-react", "tslint-config-prettier"],
    "jsRules": {},
    "rules": {
        "no-implicit-dependencies": false,
        "jsx-boolean-value": ["always", { "never": ["exact"] }],
        "jsx-no-lambda": ["always", { "never": ["onClick"] }],
        "object-literal-sort-keys": false,
        "prettier": [true, "./prettierrc"],
        "no-shadowed-variable": false,
        "interface-name": false,
        "member-access": [false]
    },
    "rulesDirectory": ["tslint-plugin-prettier"]
}

and another one called prettier.rc:

{
    "tabWidth": 4,
    "printWidth": 120
}

Run TSLint and Prettier as a Command

Inside your package.json file you can add the following commands:

"tslint": "tslint './src/**/*.{ts,tsx}'",
"tslint:fix": "npm run tslint -- --fix",
"tslint:check": "tslint-config-prettier-check ./tslint.json",
"prettier": "prettier --write --config ./.prettierrc './src/**/*.{ts,tsx}'",
  • tslint: // TODO: what does this

  • tslint:fix: fixes all the problems related to tslint.

  • tslint:check: checks if there is any part of code incorrect.

  • prettier: running this command your code will reformat.

Use it in WebStorm

The latest versions of WebStorm include already a plugin for Prettier.

Go to WebStorm > Preferences > Plugins and look for Prettier. Check is installed and also enabled as the following image:

Now you will need to add the prettier dependency. Go to WebStorm > Preferences > Languages & Frameworks > Prettier. Put the node interpreter and also the prettier folder of your current project.

Now, you will only need to press the appropiate keys. You can take a look on WebStorm > Preferences > Keymap and look for Prettier. You will see there the current keys required to execute prettier.

Last updated