Introduction
ESLint is a code static analysis tool used to identify bugs in your code and ensure your code is of high quality.
ESLint can be used to automatically fix some specific errors however not all errors can be fixed and will still require manual work.
It can also be configured to change the error checking like including/excluding specific error checks.
How to setup
This setup is based on one I did on a Nuxt project, but you should be able to follow the same instructions no matter which JavaScript project you have.
npm init @eslint/config@latest
After running the above command, you will be prompted with questions, and based on your answers, ESLint will be configured.
Below are the questions with the answers given when I used it.
Need to install the following packages:
@eslint/[email protected]
Ok to proceed? (y)
I pressed the y key and then the Enter key to continue.
How would you like to use ESLint?
- To check syntax only
- To check syntax and find problems
I selected the “To check syntax and find problems” option and pressed Enter to continue.
What type of modules does your project use?
- JavaScript modules (import/export)
- CommonJS (require/exports)
- None of these
For more modern Javascript frameworks the import/export selection is mainly used.
Which framework does your project use?
- React
- Vue.js
- None of these
The project I used this command on is Nuxt which uses Vue.js so that was the option I selected.
Does your project use TypeScript?
- No
- Yes
The project uses Typescript so I selected the “Yes” option.
Where does your code run?
- Browser
- Node
I use Nuxt for frontend only so I selected “Browser”.
Would you like to install them now?
- No
- Yes
Finally, select ”Yes” to start the installation.
Which package manager do you want to use?
- npm
- yarn
- pnpm
- bun
Finally, select ”Yes” to start the installation.
After installation, you will notice an eslint.config.js file, the one I generated had the following content.
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import pluginVue from "eslint-plugin-vue";
/** @type {import('eslint').Linter.Config[]} */
export default [
{files: ["**/*.{js,mjs,cjs,ts,vue}"]},
{languageOptions: { globals: globals.browser }},
pluginJs.configs.recommended,
...tseslint.configs.recommended,
...pluginVue.configs["flat/essential"],
{files: ["**/*.vue"], languageOptions: {parserOptions: {parser: tseslint.parser}}},
];
How to use
Here are commands that you can use to run ESLint.
To run a check across all files in the current project.
npx eslint
To run a check on a specific folder use the current path for the folder.
npx eslint ./pages
To run a check against a specific file add the path to that file.
npx eslint ./pages/about.vue
To automatically fix issues that are fixable use the following.
npx eslint --fix