Linters and formatters

A linter is a tool used to analyze code and discover bugs, syntax errors, stylistic inconsistencies, and suspicious constructs. Popular linters for JavaScript include ESLint, JSLint, and JSHint.

Most linters allow us to specify what types of bugs or inconsistencies we would like to look for. ESLint, for example, will allow us to specify a global configuration for a given code base in a root-level .eslintrc (or .eslintrc.json) file. In it, we can specify the version of the language we are using, which features we are using, and which linting rules we would like to be enforced. Here's an example .eslintrc.json file:

{
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"extends": "eslint:recommended",
"rules": {
"semi": "error",
"quotes": "single"
}
}

Here's an explanation of our configuration:

  • ecmaVersion: Here, we are specifying that our code base is written in the ECMAScript 6 (2016) version of JavaScript. This means that the linter will not complain if it sees you are using ES6 features. It will, however, complain if you use ES7/8 features, as you would expect.
  • sourceType: This specifies that we are using ES modules (imports and exports).
  • ecmaFeatures: This informs ESLint that we wish to use JSX, a syntax extension that allows us to specify XML-like hierarchies (this is used considerably in component frameworks like React).
  • extends: Here, we specify a default ruleset of "eslint:recommended", which means that we're happy for ESLint to enforce a recommended set of rules. Without this, ESLint would only enforce the rules we specify.
  • rules: Lastly, we are configuring the specific rules we wish to set on top of the recommended configuration:
    • semi: This rule relates to semicolons; in our override, we are specifying that we wish for an error to be produced in the case of a missing semicolon in case of a mere warning.
    • quotes: This rule relates to quotes and specifies that we wish for single quotes to be enforced, meaning that the linter will warn us if it sees double quotes in our code.

We can try our configuration out by writing a piece of code that intentionally breaks the rules:

const message = "hello"
const another = `what`

if (true) {}

If we install and run ESLint on this code (within bash: > eslint example.js), then we'll receive the following:

/Users/me/code/example.js
1:7 error 'message' is assigned a value but never used
1:17 error Strings must use singlequote
1:24 error Missing semicolon
2:7 error 'another' is assigned a value but never used
2:17 error Strings must use singlequote
2:23 error Missing semicolon
4:5 error Unexpected constant condition
4:11 error Empty block statement

8 problems (8 errors, 0 warnings)
4 errors and 0 warnings potentially fixable with the `--fix` option.

This details all of the errors in the syntax according to our configured rules. As you can see, it details the rule that was broken and the line the problem was found on. ESLint and other linting tools can be incredibly helpful in finding hard-to-spot syntax errors, some of which may, if left untouched, lead to difficult to debug functional bugs in the future. Linting also gives the code more consistency, enabling programmers to feel a sense of familiarity and endure less cognitive burden, as would be the case in a code base with many different syntax conventions. 

ESLint also includes a facility for fixing a subset of these syntax errors via its --fix option, although you may have noticed that only a subset of errors can be fixed this way. Others will need to be done manually. Thankfully, though, there are a number of more advanced tools available to help us out. Formatters, such as Prettier and Standard JS, will take our syntactic preferences and make active changes to our code to ensure that it remains consistent. This means that programmers don't have to burden themselves with specific syntactic rules, or endlessly change code in response to linters. They can write code in the manner they desire, and when they're done, the formatter will change the code to conform to the agreed upon syntax conventions or warn the programmer if there is a severe or invalid syntax error.

To illustrate, let's run Prettier with its default configuration on a simple piece of code:

function reverse( str ) {
return ( String( str ).split( '' ).reverse().join( '' ) );
}

When running the preceding code through Prettier, we receive the following:

function reverse(str) {
return String(str)
.split("")
.reverse()
.join("");
}

As we can see, Prettier has removed and changed some of our syntactic habits to its configured conventions. Namely, it has exchanged single quotes for double quotes, it has removed redundant parentheses, and it's made significant changes to the whitespace. The magic of formatters is that they take the pain away from the programmer. They do the work of correcting minor syntactic habits, leaving the programmer free to pursue more important work. The general trend in the industry is away from simple linters and toward more fully featured tools that combine both linting and formatting.

The decision over what syntactic conventions to abide by is configurable and entirely up to you. There are many strongly held opinions about this, but the most important tenet to uphold is consistency. I personally prefer single quotes to double quotes, for example, but if I'm working in a code base where double quotes are the established convention, then I'll have no qualms about changing my habits. Most of the time, syntactic preferences are just subjective and inherited norms, so what's important is not which norm we use, but whether or not we all abide by it.

Many of the norms we have grown used to within the JavaScript language have been guided by its dynamically typed nature. For example, we have become used to having to check manually for specific types in order to provide meaningful warnings or errors within our interfaces. For many, these norms have been challenging to adapt to, and they have grown desperate for a higher level of confidence in the types they use. Thus, people have brought various static typing tools and language extensions to JavaScript. We'll be exploring these next, and while we do, take note of how such static typing tools might change or improve your personal development feedback loop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.28.80