Four options to help you get started linting your JavaScript

August 21, 2018 0 Comments

Four options to help you get started linting your JavaScript

 

 

You can almost always bet that a good piece of writing has been the benefactor of good editing. In this respect, code is no different than prose. One of the benefits we enjoy as developers and programmers is editors, or code linters, that can be built into our workflows.

Linting is the act or process of checking your code for errors of any kind. There are many thoughts about how to optimize the effectiveness of a given piece of code. But checking to make sure it’s error-free and adheres to a particular style guide is the baseline. Sometimes this is a matter of consistency and readability, sometimes it’s a matter of making the code actually run in the first place.

When it comes to JavaScript linting, there are a handful of tools that stand apart. Let’s look at four linters that can help you get started or refine your linting process: JSLint, standardJS, JSHint, and ESLint.

JSLint was created in 2002 by Douglas Crockford, who also wrote what is arguably one of the best books on JavaScript. JSLint brings simplicity and speed to the table. But it is also highly opinionated, which can be a blessing or a curse.

JSLint consists of a single page site which is dominated by a text field where you can paste your code. Click the ‘JSLint’ button and any errors, stylistic, syntactic, or otherwise will be displayed under the text field. Under the text field is a small list of options, configurable by checkboxes. Options include tolerating extra whitespace, use of the ‘this’ keyword (which is discouraged by Crockford in his talks), and inclusion of Node.js.

If you’re not beholden to any particular style guide and you want a reliable source to check your code for you, JSLint is a great option. It is particularly effective for testing snippets of code or if you’re looking for a way to quickly lint small projects — maybe a single page static site that only contains one JavaScript file.

Based solely on GitHub stars, standardJS is the most popular option, coming in at almost 19,000 stars. It is completely opinionated, meaning it isn’t customizable at all. But, if you’re not beholden to any particular style guide this can be a blessing. It comes in the form of a Node CLI, and can be installed globally or as a development dependency using your terminal or command line of choice:

$ npm install standard --global
// or
$ npm install standard --save-dev

Because standardJS has Node and npm as prerequisites, and because it’s run from the command line or by npm script, the bar is raised slightly from JSLint’s level. But because its not configurable, you don’t have much else to worry about. You can run it from the command line as a one word command and it will check every file with a ‘.js’ extension in your current working directory.

Any errors it finds will be printed to your terminal or command line. You can expect to see output similar to this example from the standardJS documentation:

$ standard
  Error: Use JavaScript Standard Style
  lib/torrent.js:950:11: Expected '=' and instead saw ''.

If you need to specify a file or directory, you can include the path as an argument and use wild cards. It also accepts wildcards. In this example, standardJS will look for and lint any JavaScript files in the ‘src’ directory and its subdirectories:

$ standard "src/*/.js" --fix

The ‘ — fix’ flag after the file path is the option to automatically fix errors as they’re found. This can be a great time saver but it also could be a great learning exercise to fix the errors yourself.

If you want to explore the conventions and rules standardJS uses before deciding whether to use it, a full list can be found here. StandardJS is a great option for those of you looking for a quick and reliable way to get started with a JavaScript linter.

JSHint began as a fork of JSLint. The goal was to make a more configurable linter. If you’ve been using standardJS, or another opinionated linter, and you’re looking for a way to start customizing your own linting rules, JSHint might be for you. It features most of the benefits of the aforementioned linters and then some.

Like JSLint, the JSHint homepage features a text field where you can paste code. The ‘Metrics’ field to the right of the text field will update in real time as you type, tallying a running list of statistics about your code, such as a count of how many functions it contains. Of course, it also displays any linting errors it finds.

If you don’t like the copy/paste methodology and you want to bake it into your project, JSHint can be installed globally or as a project dependency using npm:

$ npm install jshint --global
// or
$ npm install jshint --save-dev

Once installed, you’ll use the CLI to lint your code. Here are two example commands that check a single file and a directory, respectively:

$ jshint index.js
// or
$ jshint src/

In the first example, JSHint will lint the ‘index.js’ file and in the second it will recursively search the ‘src/’ directory and lint any JavaScript files it finds. JSHint will print any errors it finds in your terminal.

If you don’t care about customization, JSHint can be used as described in the above examples and it will work just fine. But, from here the complexity can ramp up significantly because JSHint is completely configurable and it also exposes an API, meaning it can be used as a JavaScript module in your own JavaScript files.

A custom configuration, which should be stored in a file named ‘.jshintrc’, file might look like this:

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

This example, from top to bottom, sets the ECMAScript version at 5, requires the use of three equals signs ( = or !) as opposed to two (== or !=) when comparing values, and enforces strict mode. You can include your custom configurations by specifying the path to your ‘.jshintrc’ file behind a ‘ — config’ flag at the command line or declaring them as the ‘jshintConfig’ attribute in your projects ‘package.json’ file. JSHint will use its default options for any rules you don’t customize.

The command line option might look like this:

// looks for '.jshintrc' in the current directory
$ jshint --config './.jshintrc'

While the ‘package.json’ option might look like this:

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

You can use these basics to get started down the road of customizing your own linting rules with JSHint. If you’re looking for more, the official docs contain an exhaustive description of how to use the JSHint API and all the ways it can be customized to fit your needs.

GitHub stars aside, when it comes to JavaScript linting ESLint is probably the linter seen the most in the wild and is going to be the go-to for a lot of folks. In its own documentation it compares itself to JSLint and JSHint in regard to the methods it uses for parsing JavaScript. And, similar to JSHint, you ease in by using defaults and add customizations as your preferences or needs change.

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

$ npm install eslint --save-dev
// or
$ npm install eslint --global

If you install ESLint globally, its configurations will apply to any and all project files you run it against. But if you want different configurations for different projects, you can install it as a development dependency and create a different configuration file for each project. Be aware that if ESLint is installed as a project dependency, as opposed to globally, you need to run the executable from your ‘nodemodules’ folder like so:

$ ./nodemodules/.bin/eslint --init

When you run the above command, you’ll be walked through configuring ESLint by a series of questions. (Note: Regardless of how much you plan on customizing your linting rules, you must start with this step because ESLint needs the ‘.eslintrc’ file that will be generated by this process before it can lint your code.)

The first question asked of you is how to configure ESLint. You have three options: Use a popular style guide, answer questions about your style, or let ESLint configure itself for you by inspecting your files to decide how to set up the rules. If the prospect of configuring it yourself right off the bat seems intimidating, you can fall back on using a popular style guide developed by one of a few known organizations.

Regardless of which path you go down, ESLint will use your answers to generate a file named ‘.eslintrc’ in the current working directory. This is the file you’ll modify if you want to make changes to the linting rules later on down the road.

Here’s an example ‘.eslintrc’ file in JSON format that uses the default Airbnb JavaScript style guide rules and includes two custom rules to turn off strict mode and allow console.log() statements:

{
  "extends": "airbnb-base",
  "rules": {
    "strict": "off",
    "no-console": "off"
  }
}

If you choose to answer questions about your style it will ask you such things as which ECMAScript version you’re using, whether you prefer tabs or spaces, semicolons or not, and whether you use JSX and/or React. ESLint’s out-of-the-box support for React and supplementary plugins are likely going to make it the best choice for React developers. At least for those just getting started with linting.

After ESLint is installed and an ‘.eslintrc’ file has been generated, you can use the CLI to get started linting your code. ESLint looks for your ‘.eslintrc’ file by default so you don’t need to specify any configurations at the command line. But you can use various flags to alter how ESLint behaves. In the example below, the ‘ — quiet’ flag tells ESLint to only display errors as opposed to both warning and errors. The ‘ — fix’ flag tells it to attempt to automatically fix any errors it finds.

// run eslint against file1.js
$ ./nodemodules/.bin/eslint file1.js
// run eslint against file1.js and file2.js with flags to modify behavior
$ ./nodemodules/.bin/eslint file1.js file2.js --quiet --fix

As with the other CLIs we’ve discussed, you can use wild cards and file paths instead of specific file names if need be. Although ESLint is highly configurable, it eases the learning curve by using an approachable setup guide for its default method of configuration. If you’re looking to really dig in with customizations, the official documentation contains great explanations of everything you can do with ESLint.

In summary:

  • JSLint is great for checking snippets or single files. One of its potential downsides is that it isn’t suitable for large projects.
  • StandardJS is ideal for those who want to get started with little to no fuss and/or build a linter into their workflows and build scripts. But, it’s not configurable. So if you need to make custom rules you’ll probably want to look at JSHint or ESLint.
  • JSHint can also be installed through npm and its linting rules are completely configurable. This could be good or bad, depending on your needs and skill level. You could start with the default rules and customize as needed. It also features a single page site you can use to lint snippets or single files.
  • ESLint can be installed through npm and built into workflows just like JSHint. And the question and answer format of its CLI can help you learn as you get started. In its out-of-the-box form it includes industry standard, open source style guides and linting rules that can be applied to any project.

All four of the linters we’ve looked at are reliable and reputable by virtue of being used and developed by well-known people and organizations in the web development community. Anyone would be well served by any of them. If you’ve mastered the basics discussed in this article, a great next step would be learning how to integrate them further into your workflow using npm scripts or a bundler like Webpack.

Any tool is only as good as the use you get out of it. This is true for linters and for the code they help you perfect. Even if you’re developing alone and don’t need to worry about code consistency across a team of developers, you can still benefit from a built-in editor. It’s an incredibly effective way to learn to write JavaScript correctly. Regardless of which linter you use, using a linter can only help you. You can bet the quality of your code will improve, as will your skill as a developer.

LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single page apps.

Try it for free.


Tag cloud