What is Eslint and why do you need it?
Most of you (developers), know Eslint as a VS Code extension for making your code look prettier, generating code suggestions, avoiding bugs, and so on. Yes, Eslint is a great tool to achieve all the above-mentioned functionalities. There is much more that you can control on how to use it for your project.
How does it work?
Eslint is a linter for ECMAScript. It parses raw code into Abstract Syntax Tree. And this is used for forming the lint rules. Having said that, it is flexible and configurable. You can either install it as a node package in your project or as an extension on your IDE.
How can we configure Eslint for our project?
There are multiple ways in configuring the Eslint for our project. Using YAML files, JSON files, or js files. In my case, I found this configuration in a work project and then explored the same to understand it better. Install eslint using npm or yarn, any package manager, and define a configuration file. Create an eslintrc.js or eslintrc.json or eslintrc.yaml file to write your rules. A basic JSON configuration file looks something like the one below.
module.exports = {
"extends": "eslint:recommended",
"rules": {
// enable additional rules
"indent": ["error", 4],
"linebreak-style": ["error", "unix"],
"quotes": ["error", "double"],
}
}
Example Use Case :
For react projects that use react above v17, eslint is added as a dependency. Hence it yells at us saying that the 'React' must be in scope when using JSX . This message has led me to learn more about eslint. I wasn't writing my Browser Router in JSX in first place and it took about 15 minutes for me to understand that this was optional and that I could avoid this bug by simply switching off some rules in eslint. In order to do that, navigate to node-modules in your IDE(V S Code in my case). Find the 'eslint-config-react-app' module and open its index.js file. Here you would find some rules with respect to how it is configured for the current react project. Switch off the below rules to avoid the above-highlighted error.
I found this interesting article about creating your own custom eslint config package here.
Refer to the official documentation to learn more and explore options to experiment in your project.
I hope this was helpful. Thank you. Happy Learning!