Setting ESLint on a React Typescript project
Introduction
After struggling a lot trying to install and understand ESLint on my React Typescript project, I decided to create a definitive guide to setting ESLint to a React Typescript project.
The main goal of this tutorial is to set up step-by-step and explain every line added or executed, instead of just giving you a bunch of files with a lot of configurations and expecting that you will be able to understand what and how things are happening.
So, let’s start!
Prerequisites
Note: You need Node version >= 10 installed. So, if you don’t have it, please go to the NodeJS website, and download and install it on your local machine. (https://nodejs.org/en/)
Step 1: Create a React Project with Typescript
The following command will create a project inside a folder my-app.
On the terminal, run:
npx create-react-app my-app --template typescript
Step 2: Removing the pre-set ESLint configuration from React project
React comes with an eslint configuration pre-setted. Let’s remove this configuration so we can set a better one. To do this, remove the following code from the ‘package.json’ file
"eslintConfig": {
"extends":[
"react-app",
"react-app/jest"
]
}
Step 3: Install ESLint package
Inside the project directory, open a terminal.
On the terminal, run:
npm install eslint --save-dev
After running it, you will see that “eslint” was added as a development dependency on the ‘package.json’ file
"devDependencies": {
"eslint":"^7.20.0"
}
PS: You can ignore it if the version doesn’t match the example shown above.
Step 4: Setup ESLint
Inside the project directory, open a terminal.
On a terminal, run:
npx eslint --init
When running this command, you will need to answer some questions about the configuration:
How would you like to use ESLint?
Select: To check syntax, find problems, and enforce code styleWhat type of modules does your project use?
Select: JavaScript modules (import/export)Which framework does your project use?
Select: ReactDoes your project use TypeScript?
Select: YesWhere does your code run?
Select: BrowserHow would you like to define a style for your project?
Select: Use a popular style guideWhich style guide do you want to follow?
Select: Airbnb: https://github.com/airbnb/javascriptWhat format do you want your config file to be in?
Select: JSON
After this, it will check the dependencies that need to be installed and then will ask:
Would you like to install them now with npm?
Select: Yes
Then, it will install all the packages needed. After the installation process, the ‘devDependencies’ on the “package.json” file should look like this:
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.15.1",
"@typescript-eslint/parser": "^4.15.1",
"eslint": "^7.20.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.22.0",
"eslint-plugin-react-hooks": "^4.2.0"
}
PS: You can ignore if the version doesn’t match with the example shown above.
Step 5: Running ESLint
Inside the project directory, open a terminal.
To run ESLint and see what errors it is pointing, just run:
npx eslint <targetFile>
To automatically fix some errors, you can use ‘--fix’:
npx eslint <targetFile> --fix
If you want to ignore warnings, you can use ‘ --quiet’
npx eslint <targetFile> --quiet
Step 5.1: Let’s Run!
If we just run the eslint to the whole files inside our ‘src’ directory, it will point 35 errors. WOW!
npx eslint src/*
ESLint output:
Running with auto-fix, it gets less scary, but we still have 22 errors to solve. OMG!
npx eslint src/* --fix
ESLint output:
So, we ran through all those steps and just the ‘Hello World’ Project of ReactJS with Typescript gave us all these errors. And most of them make no sense, like extension file errors or even the use of React itself.
‘React’ was used before it was defined no-use-before-define
JSX not allowed in files with extension ‘.tsx’ react/jsx-filename-extension
Frustrating, no?
The good news is that I’ve already been through this hell to solve these problems and now I will help you finish all the configuration so we can use ESLint properly. Let’s face each problem and what we need to do to solve it!
Solving remaining problems
Problem: “‘no-use-before-define”
Error sample: ‘React’ was used before it was defined
Solution
On ‘eslintrc.json’, over “rules”, add the following:
"rules": {
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": ["error"]
}
The explanation is on this StackOverflow post (https://stackoverflow.com/questions/63818415/react-was-used-before-it-was-defined/64024916#64024916)
Problem: “‘react/jsx-filename-extension”
Error sample: JSX not allowed in files with extension ‘.tsx’
Solution
On ‘eslintrc.json’, over “rules”, add the following:
"rules":{
…
"react/jsx-filename-extension": [ "warn", {"extensions": [".tsx"]} ]
}
Problem: “import/no-unresolved”
Error sample: Unable to resolve the path to module ‘./App’
Solution
- Inside the project directory, open a terminal and install the eslint-import-resolver-typescript package
npm install eslint-import-resolver-typescript --save-dev
- On ‘eslintrc.json’, Add a new property “settings” to the JSON, as follow:
"settings": {
"import/resolver": {
"typescript": {}
}
}
Problem: “import/extensions”
Error sample: Missing file extension ‘tsx’ for ‘./App’
Solution
On ‘eslintrc.json’, over “rules”, add the following:
"rules":{
…
"import/extensions": [
"error",
"ignorePackages",
{
"ts": "never",
"tsx": "never"
}
]
}
Problem: “no-undef”
Error sample: ‘test’ is not defined
Solution
On ‘eslintrc.json’, over “extends”, add “plugin:@typescript-eslint/recommended”:
"extends": [
…
"plugin:@typescript-eslint/recommended"
],
Problem: “no-shadow”
Error sample: ‘Enum’ is already declared in the upper scope
Solution
On ‘eslintrc.json’, over “rules”, add the follow:
"rules":{
…
"no-shadow": "off",
"@typescript-eslint/no-shadow": ["error"]
}
The explanation is on this stackoverflow post (https://stackoverflow.com/questions/63961803/eslint-says-all-enums-in-typescript-app-are-already-declared-in-the-upper-scope)
Problem: Any error over files that are not ‘js’,’jsx’, ‘ts’, or ‘tsx’ extension files
Solution:
You can avoid ESLint to look over some files by adding it on the ‘.eslintignore’ file.
So,
- Create a ‘.eslintignore’ file in the root of your project
- Add the follow text to it:
*.css
*.svg
Extra:
Some nice rules to apply
Force all functions have explicit return type
On ‘eslintrc.json’, over “rules”, add:
"rules":{
...
"@typescript-eslint/explicit-function-return-type": [
"error",
{
"allowExpressions": true
}
]
}
Note: By enabling this rule, it will generate some ESLint errors that will be fixed by adding explicitly the return type of the functions on your code.
Max length of line code
On ‘eslintrc.json’, over “rules”, add:
"rules":{
…
"max-len": ["warn", { "code": 80 }]
}
React Hooks rules
On ‘eslintrc.json’, over “plugins”, add:
"plugins": [
…
"react-hooks"
],
On ‘eslintrc.json’, over “rules”, add:
"rules":{
…
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
Some rules to ignore:
Prefer use of default export
On ‘eslintrc.json’, over “rules”, add:
"rules":{
…
"import/prefer-default-export": "off"
}
Prop Types rules
On ‘eslintrc.json’, over “rules”, add:
"rules":{
…
"react/prop-types": "off"
}
Conclusion
So, with these configurations you will improve your code quality in your ReactJS with Typescript projects. Hope you enjoy! :)
VS Code: execute ESLint with auto fix in a file when save
As a plus, I will show you how to configure auto-fix on VS Code, but is an optional step, if you want to run ESLint with auto-fix every time you save your code.
- Create a ‘.vscode’ folder on the root of the project
- Create a ‘settings.json’ file inside .vscode/ folder and insert the follow code on it:
{
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
"editor.formatOnSave": true,
"eslint.alwaysShowStatus": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
- Install VS Code ESLint extension
You can go to VS Code ‘Extensions’ section and install it manually:
Or launch VS Code Quick Open (Ctrl+P) AND Run the follow command:
ext install dbaeumer.vscode-eslint
- Allow ESLint extension usage on VS Code:
For the first time that you are using it, ESLint extension will be blocked. You should then allow it by:
1. Click on the status bar icon.
2. A popup will appears. Select ‘Allow’ option.
Done! Now every file saved will fix the code with the ESLint rules that can be fixed automatically.
Comments
Post a Comment