I recently added two major static analysis tools to my project RefactorCode : Prettier and ESLint.
It allows contributors working on the project to maintain the quality of the code by fixing formatting issues and common code errors. This means that I can simply run a command to check if the code is consistent, without looking at each file to see if it fits the guidelines.
Here's how I did it:
I installed Prettier and Eslint through npm:
npm install --save-dev prettier eslint eslint-config-prettier
We are also installing eslint-config-prettier
for them to work together and not interfere with each other.
Add prettier config and ignore files (Check prettier docs for more info):
node --eval "fs.writeFileSync('.prettierrc','{}\n')"
node --eval "fs.writeFileSync('.prettierignore','# Ignore artifacts:\nbuild\ncoverage\n')"
...And you are pretty much done for Prettier, you can call format the files using the following command:
npx prettier . --write
You can also add a script to run it which I will get into later.
Now let's continue with ESLint
Run the setup for ESLint:
npx eslint --init
Complete the setup based on your requirements, here's how I did it for my project:
I added the files and folders to not be linted:
I then added scripts in package.json
to make it easier to run them:
"scripts": {
"format": "prettier --write \"**/*.{js,ts,html,css,md,json}\"",
"lint": "eslint . ",
"lint:fix": "eslint . --fix "
},
When I ran Prettier for the first time, there were a lot of white spaces issues that were fixed, I checked if the program still worked properly and committed the changes. I did the same for ESLint. There were some import errors, so I fixed them manually.
After checking to see if the program still ran properly, I committed all the changes and merged it to the main branch.
There is also a way to integrate these tools with VS Code, you can install their extensions from the VS Code Marketplace:
Create a .vscode/settings.json
file within the root directory of your project if you want to specify the extension settings only for your current project.
Here is the configuration I used for it to format and lint on save:
// .vscode/settings.json
{
// Enable format on save
"editor.formatOnSave": true,
// Set Prettier as the default formatter
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
// Enable ESLint to auto-fix issues on save
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.organizeImports": true
}
}
Overall, I think tools are great. It fixed a lot of formatting errors and issues that I otherwise wouldn't have noticed. I am going to use them when starting a new project from now on.