Logo

dev-resources.site

for different kinds of informations.

Configure Eslint, Prettier and show eslint warning into running console vite react typescript project

Published at
6/6/2024
Categories
eslint
prettier
gorupimport
showeslintwarningintoconsole
Author
khalid7487
Author
10 person written this
khalid7487
open
Configure Eslint, Prettier and show eslint warning into running console vite react typescript project

Creating a React application with Vite has become the preferred way over using create-react-app due to its faster and simpler development environment.Although vite projects by default offer eslint support but it is very simple setup which is not very helpful so far.

In this guide this i will go through config eslint with prettier groups import ad show eslint warning into console in react + typescript which is create by vite.

Assuming you already have your React Vite project set up (using npm create vite@latest), the first step is to install Vitest:

Setting up Vite eslint with yarn install:

yarn add eslint-import-resolver-typescript eslint-plugin-import eslint-plugin-prettier eslint-plugin-react-refresh prettier typescript-eslint

For showing eslint and typescript error and warning into console we need to add another library below:

yarn add vite-plugin-checker

Now time to update tsconfig.json file:

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "baseUrl": "src",
    "paths": {
      "*": ["*"]
    },
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src", "vite.config.ts"],
  "exclude": [
    "node_modules",
    "./node_modules",
    "./node_modules/*",
    "./node_modules/@types/node/index.d.ts"
  ],
  "references": [{"path": "./tsconfig.node.json"}]
}
Enter fullscreen mode Exit fullscreen mode

Note: Here, i added basurl as src and and path accept whatever i have set in vite.config.ts. For example, I have a folder name component and @core folder now i want to import it as same group during that time it will be helpful.

Enough talk let's configure vite.config.ts:


import {defineConfig} from 'vite'
import react from '@vitejs/plugin-react'
import checker from 'vite-plugin-checker'

export default defineConfig({
  plugins: [
    react(),
    checker({
      typescript: true,
      eslint: {
        lintCommand: 'eslint "./src/**/*.{ts,tsx}"',
      },
    }),
  ],
  resolve: {
    alias: {
      images: '/src/images',
      component: '/src/component',
      '@core': '/src/@core',
    },
  },
})
Enter fullscreen mode Exit fullscreen mode

now we need to update .eslintrc.cjs file:

module.exports = {
  root: true,
  env: {browser: true, es2020: true},
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react-hooks/recommended',
  ],
  parserOptions: {
    project: './tsconfig.json',
    tsconfigRootDir: __dirname,
  },
  ignorePatterns: ['dist', '.eslintrc.cjs'],
  parser: '@typescript-eslint/parser',
  plugins: ['react-refresh', 'import', 'prettier', 'react', '@typescript-eslint'],
  rules: {
    'react-refresh/only-export-components': ['warn', {allowConstantExport: true}],
    'no-console': 'warn',
    'arrow-body-style': ['warn', 'as-needed'],
    'no-empty-function': 'error',
    quotes: ['warn', 'single', {avoidEscape: true}],
    'prefer-const': 'off',
    'no-dupe-keys': 'warn',
    'react/react-in-jsx-scope': ['off'],
    'no-duplicate-imports': ['warn'],
    '@typescript-eslint/no-unused-vars': ['warn'],
    '@typescript-eslint/no-explicit-any': ['error'],
    'valid-typeof': ['error', {requireStringLiterals: true}],
    'prettier/prettier': ['warn'],
    'import/order': [
      'warn',
      {
        groups: ['builtin', 'external', 'internal', ['parent', 'sibling', 'index']],
        'newlines-between': 'always',
        pathGroups: [
          {
            pattern: '@core/**',
            group: 'internal',
            position: 'after',
          },
        ],
        pathGroupsExcludedImportTypes: ['internal'],
      },
    ],
    'import/no-named-as-default-member': ['off'],
    'import/no-anonymous-default-export': [
      'error',
      {
        allowArray: false,
        allowArrowFunction: false,
        allowAnonymousClass: false,
        allowAnonymousFunction: false,
        allowCallExpression: true,
        allowNew: false,
        allowLiteral: false,
        allowObject: false,
      },
    ],
  },
  settings: {
    react: {
      version: 'detect',
    },
    'import/resolver': {
      typescript: {
        // @alwaysTryTypes always try to resolve types under `<root>@types`
        // directory even it doesn't contain any source code, like `@types/unist`
        alwaysTryTypes: true,
        project: './tsconfig.json',
        extensions: ['.ts', '.tsx'],
      },
    },
  },
}

Enter fullscreen mode Exit fullscreen mode

We need to update .prettier.cjs file as well:

module.exports = {
  semi: false,
  singleQuote: true,
  jsxSingleQuote: true,
  bracketSpacing: false,
  jsxBracketSameLine: false,
  arrowParens: 'avoid',
  useTabs: false,
  tabWidth: 2,
  printWidth: 100,
  trailingCommas: {
    array: true,
    object: true,
    function: false,
  },
}
Enter fullscreen mode Exit fullscreen mode

Import as a group is responsible for the below eslint rules:

'import/order': [
'warn',
{
groups: ['builtin', 'external', 'internal', ['parent', 'sibling', 'index']],
'newlines-between': 'always',
pathGroups: [
{
pattern: '@core/**',
group: 'internal',
position: 'after',
},
],
pathGroupsExcludedImportTypes: ['internal'],
},
],

here we need to specifics the group here which group i want. if your import group is not setup correctly this will show you warning into your console.

We may check this reference from github: https://github.com/khalid7487/study/tree/master/React/vites-config-eslint

prettier Article's
30 articles in total
Favicon
VSCode Prettier format on save
Favicon
Beyond Spellcheck: How Static Analysis Tools Enhance Collaboration in Coding
Favicon
Setup Eslint Prettier in a TypeScript project with mongoose ODM
Favicon
Vue3 + ESLint 9.13.0 + Prettier +TypeScript and VSCode Autoformat on Save
Favicon
Configurando Prettier, ESLint y Husky en Angular
Favicon
Setup Prettier Pada Nextjs Tailwind Project
Favicon
Regras customizáveis para Prettier + Eslint em React
Favicon
Useful VS Code Extensions for JS
Favicon
ESLint x Prettier: The Right Way To Start A JavaScript Project
Favicon
How to Set Up ESLint and Prettier in a TypeScript Project
Favicon
Customizable rules for Prettier + Eslint in React
Favicon
Tired of Messy Code?🥴
Favicon
Streamline Your Tailwind CSS Workflow with Prettier Plugin Enhancements
Favicon
Why Do I Love Code Formatters?
Favicon
How to set up Eslint and prettier
Favicon
Configure Eslint, Prettier and show eslint warning into running console vite react typescript project
Favicon
Building Vue3 Component Library from Scratch #11 ESlint + Prettier + Stylelint
Favicon
Setup Eslint + Prettier for code standardization in React
Favicon
Setup Eslint + Prettier para padronização de código em React
Favicon
How to prevent Prettier putting a full stop on a new line after a link
Favicon
Moving "server-only" to the top of the imports
Favicon
My opinion about opinionated Prettier: 👎
Favicon
Setting Up Express development environment (Typescript, Eslint, Prettier)
Favicon
Biome.js : Prettier+ESLint killer ?
Favicon
Most elemental code formatting for Typescript/Javascript: .editorconfig vs prettier
Favicon
Setup Next.js 14 project with Eslint + Prettier + Tailwind CSS
Favicon
Prettier for PHP File Formats in VSCode
Favicon
Angular 14 + Prettier + Husky Setup
Favicon
แชร์ไฟล์ Prettier ง่ายๆ แค่ปลายนิ้ว!
Favicon
NextJS 14'te Kod Kalitesini Artırma: ESLint, Prettier ve Husky Kullanımı

Featured ones: