This video is available to students only

ESLint

Code linting and ensuring code style.

ESLint can be found at https://eslint.org.

Linters are used to analyze our source code to find common bugs, keep coding styles consistent, and ensure we're using good practices. ESLint is the most popular linter in the JavaScript community. In this lesson, we'll take a look at implementing an ESLint configuration and running linting.

Installing ESLint#

ESLint can be installed as a devDependency by running yarn add eslint --dev. ESLint comes with a nice initialization script to get started. Run yarn eslint --init.

We'll be asked a bunch of questions about our project. For Scroller we can use the following settings:

  • How would you like to use ESLint? To check syntax, find problems, and enforce code style

  • What type of modules does your project use? JavaScript modules (import/export)

  • Which framework does your project use? React

  • Does your project use TypeScript? Yes

  • Where does your code run? Browser

  • How would you like to define a style for your project? Use a popular style guide

  • Which style guide do you want to follow? Airbnb

  • What format do you want your config file to be in? JavaScript

  • Would you like to install them now with npm? Yes

A .eslintrc.js will be created, which contains our configuration for ESLint.

Adding a lint command#

Update our package.json file to include a lint script. In the "scripts" section add "lint": "eslint \"src/*\"", to run linting on all files in the src/ directory (we need to escape the double quotes because your terminal will try to resolve the glob * itself. With quotes around \"src/*\" we ignore the terminal's glob resolution and use NodeJS's instead).

Run yarn lint to check linting errors.

A screenshot showing linting errors.

Adding new rules#

eslint init provided a couple of default rule sets. The first is plugin:react/recommended, the recommended linting rules for React, and airbnb which is a popular code standard for JavaScript.

The airbnb configuration enforces single quotes when creating strings ', but we've been using double quotes in Scroller ". In the rules section, of our .eslintrc.js file, add a rule to create an error if we don't use double-quotes. Rules we specify will overwrite the default rules given from the extended configurations.

We also can turn rules off by adding rules with an "off" value. Override a few of airbnb's configurations to match our style.

 

This page is a preview of Creating React Libraries from Scratch

Start a new discussion. All notification go to the author.