Linting javascript [correct way]

Hi devs, we all love the simplicity and easiness in writing code in javascript language. No doubt it has become a universal language for devs all around the world. But every thing comes at a cost, loose coupling and simplicity of language also makes it vulnerable to bugs. Thanks to Nicholas C. Zakas, we have something wonderful to rescue, it’s eslint.


Forget about JavaScript formatter or beautifier.

Below are the steps to starting using eslint a node project.

Step 1. Installing Eslint: 
You have option to install locally or globally:

npm install eslint --save-dev

To integrate within vscode, install eslint extension.

Step 2. Add linting rules:
Create a .eslintrc file in the project folder, this will make your rules project specific.

To know about various rules click here.

You can also simply follow the best practices rules around:

We are going to use JS standard as a sharable config, detailed here:

npm install --save-dev eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node

add "extends": "standard" to the .eslintrc file.

Step 3. Configure VS code:

First of all, disable all JavaScript formatter or beautifier than you might have mistakenly installed in VS code.

Add the below to user setting in vs code, this will enable auto formatting as per eslint rules that you have defined. And reload your project.

{
"eslint.run": "onSave",
"eslint.autoFixOnSave": true
}

Now you are all set.

Extra stuff:

  • Define environment in eslint:
{
"env": {
"browser": true,
"node": true,
"mocha":true
}
}
  • Define globals in eslint:
{
"globals": {
"var1": true,
"var2": false
}
}
  • You can also add git pre-commit hooks in your project which checks for eslint errors. And if any found would not allow the dev to commit.

Thanks for reading to so far. If you like the article, please give a thumbs up! :D