Eslint typescript react example

Setup React App with TypeScript, ESLint and Prettier

Let’s create development configuration for a React application with TypeScript, ESLint and Prettier.

Create React App

Let’s create a new project with create-react-app tool.

npx create-react-app my-app --template typescript

It means that all of the configuration will be exposed to you (full project control).

ESLint

ESLint will statically analyze our code to quickly find problems.

npm i --save-dev typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-config-airbnb-typescript eslint-plugin-react-hooks eslint-plugin-jest eslint-plugin-import

Then we can install the packages for Airbnb config:

npx install-peerdeps --dev eslint-config-airbnb

Prettier

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

npm i --save-dev prettier eslint-config-prettier eslint-plugin-prettier

ESLint config

Let’s create .eslintrc file in the root of the project and paste next code:

// .eslintrc  "parser": "@typescript-eslint/parser", "parserOptions":  "ecmaFeatures":  "jsx": true, "useJSXTextNode": true >, "ecmaVersion": 2018, "sourceType": "module", "project": "./tsconfig.json" >, "extends": [ "airbnb-typescript", "airbnb/hooks", "plugin:@typescript-eslint/recommended", "plugin:jest/recommended", "prettier", "prettier/react", "prettier/@typescript-eslint", "plugin:prettier/recommended" ], "plugins": ["react", "react-hooks", "@typescript-eslint", "jest"], "env":  "browser": true, "es6": true, "jest": true >, "globals":  "Atomics": "readonly", "SharedArrayBuffer": "readonly" >, "rules":  "linebreak-style": "off", "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "warn", "prettier/prettier": [ "error",  "endOfLine": "auto" > ], "import/extensions": [ "error", "ignorePackages",  "js": "never", "jsx": "never", "ts": "never", "tsx": "never" > ] > >

and add .eslintignore file for prevent lint checking for specific files:

// .eslintignore .idea .storybook .config node_modules/* config/* public/* scripts/* src/react-app-env.d.ts src/reportWebVitals.ts

Prettier config

Let’s create .prettierrc file in the root of the project and paste next code:

// .prettierrc  "arrowParens": "always", "singleQuote": true, "printWidth": 100, "jsxBracketSameLine": false, "trailingComma": "none" >

Scripts

In package.json you can add next scripts:

Git hooks

These make sure all our commits are formatted, without having to wait for your CI build to finish.

npm install husky --save-dev

We can add the following to our package.json to have ESLint run before each commit, via husky:

"husky":  "hooks":  "pre-commit": "npm run lint && npm run test" > >

Источник

React + TypeScript + ESLint + Prettier Full Setup ✈

Introduction

Hello amazing developer 🧑‍💻, before digging into this topic let me give you a small introduction and so instructions. Don’t worry it would be quick and crisp 😉. I am Suchintan Das, a Full Stack Developer currently working over two startups. I have been into web development for past two years. Connect me on 👉Linkedin Note: I will be using a Windows machine 💻 while doing the process. So, there can be some case where the commands may differ for you if using a different machine. Please help yourself out in that case, though I will try my best to cover all such commands.

Why this configuration 🤔?

Before starting with this tutorial, it’s important to understand why we need this configuration. So, let me introduce you to these stacks individually and help you understand their benefits.

ESLint

Have you ever faced issues due to a messy code written by someone and not following the rules that are supposed to be kept in mind while writing the code 🥲? A small example —

import axios from 'axios' const component = () =>

Like here the developer forgot to add a line gap between imports and the main functional component. A similar problem is pushing a lot of console logs on production . These things are small but very irritating when the codebase evolves and many lines of code comes into it 📚. And yes , to maintain clean code they don’t need to put that much efforts, just following some rules every time make a codebase very clean 🧹. That’s the idea of ESLint and yes, you need it to make your codebase very sweet for any new developer to code 👍.

Prettier

Has the same idea as that of ESLint but their combination is really robust. Many developers likes ESLint + Prettier configuration very good when you want to make you codebase very easy for debugging and onboard .

TypeScript

I know, most of you guys would already are familiar with this framework. It’s very famous after all 🤷. But here’s a small introduction for this framework. Want to follow a structured format for your codebase where all the props , function returns etc. are setup beforehand so that , it avoids mistake ? Yes, I know it’s very awesome to work on a project where everything works in a structured way and if anything goes out of the structure, you get an error. Saves really a lot of time for debugging❗ TypeScript has interfaces , function types and many more. A small peak of it is here. apiCall.ts 📝

import axios from "axios"; import < AuthLogin, AuthRegister >from "../models/Auth"; import setAuthToken from "../utils/controllers/setAuthController"; const baseUrl: string = String(process.env.REACT_APP_SERVER_URL); export const loginauth = async (email: string, password: string) => < // console.log(baseUrl); const options: AuthLogin = < method: "post", url: `$auth/login`, data: < email, password, >, >; try < axios .request(options) .then((response) => < if (response?.status === 200) < setAuthToken(response?.data?.token); >return response?.status as Number; >) .catch(); > catch (e) < // console.log(e); >>; 
export interface AuthLogin < method: string; url: string; data: AuthLoginBody; >export interface AuthLoginBody

Источник

How to setup eslint for react typescript projects

In this article, i am going to show you how i set up basic linting with eslint for react typescript projects. There are many articles online regarding setting up eslint for react. It was a real mess and difficult to figure out which settings to use and what packages to install. After sieving through countless articles and resources, i have finally found a setup which covers all the basics in a react project. I normally use npx create-react-app [projectname] —template typescript to start my react project with typescript template. This template installs eslint for you. However, if you do not, you will need to install the eslint and typescript package. npm install eslint typescript I would recommend installing and setting up eslint for every project instead of using your own global eslint package/settings. Each project might have different requirements. Your .eslintrc file will be configured to the required linting for each of your projects. It ensures consistency in code for all developers working on the project. First, in your react project, create a .eslintrc.json file in the root directory. Next, in the json file, use the following set up. For more details on configuring eslint, you can find out more from the eslint website

< "env": < "browser": true, "es6": true, "jest": true >, "rules": < "no-console": "error", "import/first": "error", "react/prop-types": "off" >, "extends": [ "react-app", "react-app/jest", "eslint:recommended", "plugin:react/recommended", "plugin:@typescript-eslint/recommended", "plugin:react-hooks/recommended", "prettier" ], "parser": "@typescript-eslint/parser", "root": true, "plugins": ["react", "@typescript-eslint"], "parserOptions": < "ecmaVersion": 11, "ecmaFeatures": < "jsx": true >, "project": "./tsconfig.json" >, "settings": < "react": < "pragma": "React", "version": "detect" >> > 

env

Enables the use of global env variables in your code. Enabling the env variables will prevent eslint from giving errors.

rules

extends

  • react-app — Eslint configuration used by create-react-app
  • react-app/jest — Eslint configuration used by create-react-app
  • eslint:recommended — Eslint recommended configuration by eslint
  • plugin:react/recommended — Recommended react linting configs details
  • plugin:@typescript-eslint/recommended — Turns on rules from TypeScript-specific plugin. npm install —save-dev @typescript-eslint/eslint-plugin details
  • plugin:react-hooks/recommended — Eslint configuration for react-hooks by create-react-app details. Comes installed together with npx create-react-app
  • prettier — Turns off all rules that are unnecessary or might conflict with Prettier. You will need to install this package for you to use it. npm install —save-dev eslint-config-prettier
    details

plugins

Plugins from npm packages which configures and rules

  • react — For eslint-plugin-react
  • @typescript-eslint — For parser and extension @typescript-eslint/recommended

parser

  • Use @typescript-eslint/parser for typescript to work with eslint. This allows Eslint to understand TypeScript syntax. Install typescript-eslint npm install —save-dev @typescript-eslint/parser details

parserOptions

  • ecmaVersions — sets the ECMAScript version you want to support for your project
  • ecmaFeatures — set jsx to true for React
  • project — Tells Eslint where to find the root tsconfig file of your project. If you have multiple tsconfigs in the project, you can define where the tsconfigs are found. details

settings

The settings made here will be shared across all rules for plugins. For eslint-plugin-react, it will require some defaults setttings:

Remember to install vscode extension Eslint and Prettier in order for linting and styling to work. With this configuration, you are all set to write in typescript for any React projects.

You can add or remove plugins/configs which you find more suitable for your style. Enable rules like «no-console» which will give an error when compiling. Good coding practice for preventing unwanted console logs in your app. Or «import/first» where all import modules must come first at the top of the file. Catches any import errors during compilation.

Hope this article was useful for you. Leave a comment, like or share if you found it useful. 😄

Источник

Читайте также:  Сортировка по возрастанию в массиве java
Оцените статью