How to add ESlint to javascript or node project

How to add ESlint to javascript or node project

ESlint is the best tool that we can use to ensure consistent code style. In this article, you will learn how to add and set up elsint on your nodejs or javascript project.

First of all, install ESlint using npm:

npm install eslint

To set up ESlint, we should run the command below:

npm init @eslint/config

And choose:

To check syntax, find problems, and enforce code style.

CommonJS (require/exports)

None of these

We don’t use TypeScript yet, so choose No.

Choose Node

I recommend you to choose: Use a popular style guide.

Choose Standard:

I recommend choosing Javascript but be free to choose whatever you want:

Choose Yes:

I choose npm here:

When the installation is complete, you will see .eslintrc.js file in the root of your project.

If you are using jest, please install ESlint for jest:

npm i eslint-plugin-jest

Then, add lint and lint-fix command to the scripts section in the package.json file:

{
  "name": "nodejs_app",
  "version": "0.0.1",
  "description": "",
  "main": "index.js",
  "jest": {
    "clearMocks": true,
    "roots": [
      "__tests__"
    ],
    "setupFiles": [
      "<rootDir>/jest.setup.js"
    ],
    "verbose": true
  },
  "scripts": {
    "lint": "./node_modules/.bin/eslint .",
    "lint-fix": "./node_modules/.bin/eslint --fix",
    "test": "./node_modules/.bin/jest -i"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "eslint": "^8.19.0",
    "eslint-config-standard": "^17.0.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-n": "^15.2.3",
    "eslint-plugin-promise": "^6.0.0",
    "jest": "^28.1.1"
  },
  "dependencies": {
    "eslint-plugin-jest": "^26.5.3"
  }
}

Finally, make sure that your .eslintrc.js file looks like this:

module.exports = {
  env: {
    browser: true,
    commonjs: true,
    es2021: true,
    'jest/globals': true
  },
  extends: [
    'standard'
  ],
  parserOptions: {
    ecmaVersion: 'latest'
  },
  plugins: ['jest'],
  rules: {
    'jest/no-disabled-tests': 'warn',
    'jest/no-focused-tests': 'error',
    'jest/no-identical-title': 'error',
    'jest/prefer-to-have-length': 'warn',
    'jest/valid-expect': 'error'
  }
}

Now you can run ESlint from the root folder of your project:

npm run lint

You can see an example of the project here.

To set up ESlint in phpstorm see this article.

Leave a Reply

Your email address will not be published. Required fields are marked *