React-Vite + Airbnb lint 설정 에러 수정과 변경 사항 기록

김민찬·2024년 4월 23일
0

React

목록 보기
14/14
post-thumbnail

React-Vite + Airbnb lint 설정

  • 프로젝트를 하면서 React-Vite로 진행 중 원할한 협업을 위해 eslint와 prettier 설정을 하다가 에러 핸들링과 합리적이지 않다고 생각하는 lint설정을 수정해 기록해 놓는다.

에러

Parsing error - vite.config.ts

0:0 error Parsing error: ESLint was configured to run on <tsconfigRootDir>/vite.config.ts using parserOptions.project <tsconfigRootDir>/tsconfig.json

  • 이유: 이 에러는 TypeScript ESLint 설정이 tsconfig 파일에 포함되어 있지 않은 vite.config.ts 파일을 분석하려는 시도 때문에 일어난다.

  • 해결 방법: .eslintrc.cjs 파일에 있는 ignorePatterns 항목에 'vite.config.ts' 를 추가해서 해서 lint가 vite.config.ts를 무시하도록 한다.

변경 사항

import React from 'react' 강제 설정

  • React 17버전 부터를 굳이 cravite로 프로젝트를 시작했다면 jsx 변환 설정이 "runtime": "automatic"으로 되어 있기 때문에 import React from 'react'가 필요없다.
  • 필요하지 않은 'import'를 하지 않는 것이 좋다고 생각해서 'react/react-in-jsx-scope': 'off',rules에 추가했다.

semi 규칙 off

  • Vite에서 기본적으로 설정되어있는 lint 설정에서 코드에 Semi-Colon 구분자를 추천하는데 Airbnb litn 규칙에서는 추천하지 않는다.
    • 두 규칙이 충돌 해서 하나의 규칙을 따라야 했다.
  • 회사에서는 기본적으로 semi 규칙을 사용했었지만 이가 코드에 가독성에 별로 도움이 되지 않는다고 생각해서 Airbnb 규칙을 따랐다.
  • '@typescript-eslint/semi': 'off'rules에 추가했다.

함수형 컴포넌트 화살표 함수로 선언하게 변경

Function component is not a function declaration

  • 함수 선언식의 호이스팅 문제때문에 필자는 화살표을 선호한다.
    • 사람이 코드를 읽을 때 책을 읽듯이 상에서 하로 좌에서 우로 읽게 되는데, 함수 선언문은 함수 전체를 호이스팅해서 선언문이 사용하는 코드보다 아래 있어도 사용이 가능해서 흐름을 방해한다고 생각한다.
  • 코드에는 일관성이 있어야 한다고 생각해서 모든 함수를 화살표 함수로 만드는게 좋다고 생각했다.
  • 그래서 컴포넌트에 화살표 함수를 강제하도록 수정했다.
'react/function-component-definition': [
  2,
  {
    namedComponents: 'arrow-function',
    unnamedComponents: 'arrow-function',
  },
],

전체 코드

  • .eslintrc.cjs 폴더 전체 코드를 보면 다음과 같다.
module.exports = {
  root: true,
  env: { browser: true, es2020: true },
  extends: [
    'airbnb',
    'airbnb-typescript',
    'airbnb/hooks',
    'plugin:react/recommended',
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react-hooks/recommended',
  ],
  ignorePatterns: ['dist', '.eslintrc.cjs', 'vite.config.ts'],
  parser: '@typescript-eslint/parser',
  plugins: ['react-refresh', '@typescript-eslint', 'prettier'],
  rules: {
    semi: 'off',
    'react/react-in-jsx-scope': 'off',
    '@typescript-eslint/semi': 'off',
    'react/function-component-definition': [
      2,
      {
        namedComponents: 'arrow-function',
        unnamedComponents: 'arrow-function',
      },
    ],
    'react-refresh/only-export-components': [
      'warn',
      { allowConstantExport: true },
    ],
  },
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    project: './tsconfig.json',
  },
}

참고자료

profile
두려움 없이

0개의 댓글