React Native ~ Linting - rohit120582sharma/Documentation GitHub Wiki

Adding a linter to your React Native project is not mandatory, but highly encouraged. Not only does it help ensure a consistent code style throughout the project, it also highlights errors and often uncovers bad practices.

The go-to linter for JavaScript is called eslint.



Installation

First, we should install the package. For this, open your terminal, navigate to the root directory of your project and run the following:

$ npm install eslint --save-dev
$ npm install @react-native-community/eslint-config --save-dev

This will add two packages to your dev dependencies:

  • eslint - the code linter for JavaScript
  • @react-native-community/eslint-config - a community-built eslint configuration for React Native

You can always configure your own linting rules of course, but I like to start with community presets.



Configuration

Adding the configuration files

We've now installed both eslint and the community preset, but the eslint package doesn't know about the preset. In order to make eslint aware of this, we need to add a configuration file.

Create a new file in the root directory of your project and call it .eslintrc.js. If you used react-native init to create your project, then you'll already have this file, but with Expo you'll have to create it.

Open the file and add the following:

// .eslintrc.js

module.exports = {
  root: true,
  extends: '@react-native-community',
};

This lets the linter know about the configuration package we want to use.

The community package actually comes with prettier pre-installed. Prettier is another package complimentary to eslint, but it focuses on code formatting. It mostly deals how the code looks rather than its correctness. The great thing about prettier is that if you can turn on "format on save" or have a pre-commit hook that runs its before a commit so your code will always be formatted uniformly.

Prettier has very few configuration options, because their mentality is to have as few variations as possible.

Create another file in the root directory of your project and call it .prettierrc (you'll already have this file as well if you used react-native init).

Open the file and add the following:

// .prettierrc.js

module.exports = {
  bracketSpacing: true,
  singleQuote: true,
  trailingComma: 'all',
};

Adding the run script

Open the package.json in your project and add the following under the scripts section:

"lint": "eslint ."

Now you can run npm run lint or yarn lint in your terminal and the linter will report both eslint and prettier issues.


Adding it to your code editor

It's all well and good to lint your code on the command line, but ideally you'd have instant feedback while you're writing your code.

// VSCode
Code => Preferences => Extentions => ESLint
⚠️ **GitHub.com Fallback** ⚠️