What is linting and how can it help you?
Tags: javascript, typescript, codestyle, tooling
Published: 2020-02-08 11:25:26

---
title: What is linting and how can it help you?
published: true
date: 2020-01-10 00:00:00 UTC
tags: #javascript, #typescript, #codestyle, #tooling
canonical_url: https://www.mariokandut.com/what-is-linting-and-how-can-it-help-you/
---

_This article was originally published on [mariokandut.com](https://www.mariokandut.com/what-is-linting-and-how-can-it-help-you)._

In an ideal world there would be no errors, because errors are bad, especially when writing code. Some errors cause glitches that frustrate users or compromise security. The best thing is to avoid them, as good as you can. As a developer you have the benefit of modifying your workflow, hence you can easily add a linter.

Linting can help us to reduce errors and improve code quality. The definition of a linter, according to wikipedia is: _"lint, or a linter, is a tool that analyzes source code to flag programming errors, bugs, stylistic errors, and suspicious constructs."_ [wikipedia](https://en.wikipedia.org/wiki/Lint_(software))

So basically a linter is a **basic static code analyzer** , it checks your source code for programmatic and stylistic errors (wrong identitation, variable naming, ...).

For example:s

```
const msg = 'This is my first message!'
console.log(msg)
const msg = 'This is my second message!'
```

If you are using a linter you'll get an error:

```
  error: Identifier 'msg' has already been declared
```

In the javascript world there are several linters available. The most used ones are: ESLint, JSLint, JSHint and TSLint (TypeScript).

### ESLint

**Stats:** [7.381M Downloads - VS Code](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)[15.8k Github](https://github.com/eslint/eslint) ⭐

In the javascript world **ESLint** would be the most seen one. If you work with Typescript you can also use ESLint (yes, there will be a post about this. 😇). ESLint has 15.7k Stars on [Github](https://github.com/eslint/eslint) and the repository is quite active, so it's worth checking it out.

ESLint is similiar to JSLint or JSHint, but there are exceptions:

- ESLint uses [Espree](https://github.com/eslint/espree) for JS parsing.
- ESLint uses an **AST** to evaluate patterns in code.
- ESLint is **completely pluggable** , every single rule is a plugin and you can add more at runtime.

**Espree** is basically a JavaScript parser with a modular architecture based on [Acorn](https://github.com/acornjs/acorn), which is also a JS parser.

#### What is AST

AST (Abstract Syntax Tree) is used for describing a particular syntax pattern in your code, see the example AST below.

![Abstract syntax tree example](https://www.mariokandut.com/static/761b9d6a8666787a6f6a38d6ec92a9fa/b9e4f/abstract-syntax-tree-example.png "Abstract syntax tree example")

Explore the Abstract Syntax tree for your javascript code yourself, on [astexplorer.net](https://astexplorer.net/).

To get started with ESLint, install it globally or as a development dependency:

```
npm install eslint --save-dev
# or
npm install eslint --global
```

**Important:** If you install ESLint **globally** , the configuration will **apply to all projects** you run it against. If you want a different configuration for each project, you have to install it as a **dev dependency** with the flag `--save-dev`.

To start the configuration of ESLint, run the command.

```
eslint --init
```

You will be guided through a setup wizard. You always have to start with the initialization of ESLint to create the configuration file. The questions in setup wizard are quite self-explanatory:

1. How would you like to use ESLint?
2. What type of modules does your project use?
3. Which framework does your project use?
4. Do you use TypeScript in your project?
5. Where does your code run?
6. What format do you want your config file to be in?

_If some dependencies, like `eslint-plugin-react` is missing, it will prompt to install it._

After the installation, you should have a configuration file in the root folder of your project. Below you can see the basic eslint config file for a react project.

```
{
    "env": {
        "browser": true,
        "es6": true,
        "node": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended"
    ],
    "globals": {
        "Atomics": "readonly",
        "SharedArrayBuffer": "readonly"
    },
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 2018,
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
    }
}
```

#### ESLint Configuration

What configuration should you use? If you are starting from scratch with ESLint, you can base your configuration on a popular style guide. If it this sound too intimidating for you, you can also use it completely and modify your config file over time. One of the most popular style guides for Javascript is the [Airbnb Javascript Style Guide](https://github.com/airbnb/javascript).

### JSLint

**Stats:** [101k Downloads - VS Code](https://marketplace.visualstudio.com/items?itemName=ajhyndman.jslint)[3.3k Github](https://github.com/douglascrockford/JSLint) ⭐

JSLint was created in 2002 by Douglas Crockford. Maybe you know this $[book](https://amzn.to/35EuYDC) from him? Andrew Hyndman made a VS Code extension, which is used by ~101k developers. The online version of [JSLINT](https://jslint.com) features a text field, where you can check your code direct on the website. It supports ES6, _at least the good parts of it_.

**JSLint is opinionated** , which can be a blessing or a curse. If you have to use a style guide in your project, JSLint may not be the ideal tool for you. In my opinion, it's great for smaller projects, I've used it in the past with good old vanilla javascript.

### JSHint

**Stats:** [1.165M Downloads - VS Code](https://marketplace.visualstudio.com/items?itemName=dbaeumer.jshint)[8.3k Github](https://github.com/jshint/jshint) ⭐

[JSHint](https://jshint.com/) started as a fork of JSLint with the goal to make a more configurable Linter. JSHint is not opinionated like JSLint and can be customized. It also has a website with a text field to paste code and lint on the website directly, you even get some metrics about your code like how many functions your code contains and of course linting errors.

If you don't like this copy/paste method, JSHint can be installed using npm:

```
npm install jshint --global
# or
npm install jshint --save-dev
```

Once installed, you’ll use the command line interface (CLI) to lint your code, like so:

```
# check one file
jshint index.js

# check directory
jshint src
```

JSHint can be customized using a file named `.jshintrc`, see below:

```
{
  "esversion": 5,
  "eqeqeq": true,
  "strict": true
}
```

This customization sets the ECMAScript to version 5, uses `===` instead of `==` and enforces strict mode.

The config file can be created in the root folder in the project and then added to the JSHint config, with this command:

```
jshint --config './.jshintrc'
```

Or you add the config to the `package.json` like so:

```
{
  "jshintConfig": {
    "esversion": 5,
    "eqeqeq": true,
    "strict": true
  }
}
```

There are more configuration options and you can fully customize JSHint. The official [DOCS](https://jshint.com/docs/) contain all the config options and more information about the JSHint API.

### TSLint

**Stats:** [1.647M Downloads - VS Code](https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-typescript-tslint-plugin)[5.6k Github](https://github.com/palantir/tslint) ⭐

**TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.** So basically, JavaScript that scales.Typescript was developed by Microsoft and it's open source. More information in the [github repo](https://github.com/microsoft/TypeScript).

_TSLint is de facto the standard linter for TypeScript repositories and for the TypeScript implementation itself._ TSLint is maintained by [Palantir](https://palantir.github.io/tslint/) and they want to depcrecate TSLint and focus on making ESLint support TypeScript. 😀

In a recent [blog post](https://medium.com/palantir/tslint-in-2019-1a144c2317a9) the Palantir Group posted:

> [...] In order to avoid bifurcating the linting tool space for TypeScript, we therefore plan to deprecate TSLint and focus our efforts instead on improving ESLint’s TypeScript support.

So if you are using TypeScript instead of JavaScript, because of the many benefits in debugging and writing clean code, you probably already have TSLint installed.

If you are just starting out with TypeScript or want to add the TSLint to your project, you have to install it:

```
  # local
  npm install tslint typescript --save-dev
  yarn add tslint typescript --dev

  # global
  npm install tslint typescript -g
  yarn global add tslint typescript
```

The typescript package is a **peer dependency** of TSLint. This allows you to **update the compiler independently from the linter**. This also means that tslint will have to use the same version of tsc which is used to actually compile your sources.

Keep in mind that an update to the newest version of typescript with `typescript@next` can eventually cause the linter to malfunction.

### Usage

Please ensure that the **TypeScript source files compile correctly** before running the linter.

Quick Start in CLI after installing TSLint:

```
# Navigate to your sources folder
cd path/to/project

# Generate a basic configuration file
tslint --init

# Lint TypeScript source globs
tslint -c tslint.json 'src/**/*.ts'
```

The basic syntax of tslint is `tslint [options] [file ...]`.

Available parameters for `[options]`:

```
-v, --version output the version number
-c, --config [config] configuration file
-e, --exclude <exclude> exclude globs from path expansion
--fix fixes linting errors for select rules (this may overwrite linted files)
--force return status code 0 even if there are lint errors
-i, --init generate a tslint.json config file in the current working directory
-o, --out [out] output file
--outputAbsolutePaths whether or not outputted file paths are absolute
--print-config print resolved configuration for a file
-r, --rules-dir [rules-dir] rules directory
-s, --formatters-dir [formatters-dir] formatters directory
-t, --format [format] output format (prose, json, stylish, verbose, pmd, msbuild, checkstyle, vso, fileslist, codeFrame)
-q, --quiet hide non "error" severity linting errors from output
--test test that tslint produces the correct output for the specified directory
-p, --project [project] tsconfig.json file
--type-check (deprecated) check for type errors before linting the project
-h, --help output usage information
```

### TSLINT Configuration

By default, TSLint looks for a **configuration file** named **tslint.json** in the directory of the file being linted and, if not found, searches ancestor directories.

To generate a tslint config file:

```
# Generate a basic configuration file
tslint --init
```

There are plenty of different rules for the config file, which are categorized in:

- TypeScript-specific
- Functionality
- Maintainability
- Style
- Format

All the TSLint rules can be found in the [DOCS](https://palantir.github.io/tslint/rules/).

After starting tslint in the command line the CLI process may end with one of these codes:

- 0: Linting succeeded without errors (warnings may have occurred)
- 1: An invalid command line argument or combination thereof was used
- 2: Linting failed with one or more rule violations with severity error

If you use TypeScript instead of JavaScript in your project, you have to use ESLint or TSLint for type checking. Personally, I like to use TypeScript very much, it helps prevent bugs and gives a cleaner structure to the code. The downside when using TypeScript is more code, but this can be neglected with all the benefits gained.

## In a nutshell

- ESLint is a out-of-the-box solution and includes industry standards, open source style guides and custom linting rules.
- JSLint is opinionated. It's great for checking snippets of code or single files. One of the potential downsides is that it is not suitable for large or enterprise projects.
- JSHint is like JSLint, but can be fully customized.
- TSLint is the linter for TypeScript projects. An industry standard maintained by Palantir, but it will be deprecated in favor of ESLint TypeScript support.

My recommendation is to use TypeScript and hence TSLint or ESLint with TypeScript support. If you want to use a linter in a JavaScript project, I'd recommend using ESLint.

Thanks for reading and if you have any **questions** , use the **comment** function or **send me a message** on twitter **[@mariokandut](https://www.twitter.com/mariokandut)**.

References: [Farley Reynolds](https://blog.logrocket.com/four-options-to-help-you-get-started-linting-your-javascript-b4b829828648/), [Colby](https://www.freecodecamp.org/news/what-is-linting-and-how-can-it-save-you-time/), [Google ESLint Config](https://github.com/google/eslint-config-google), [AirBnB ESLint Config](https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb), [Robin](https://www.robinwieruch.de/webpack-eslint/), [Palantir](https://palantir.github.io/tslint/) and many more.