티스토리 뷰

기존 자바스크립트로 작성된 코드를 타입스크립트로 마이그레이션을 진행했다.

 

typescript 환경 eslint를 추가하기 위해 명령어를 입력하자 오류가 발생했다.

[eslint] Failed to load plugin '@typescript-eslint' declared in '.eslintrc.json': Class extends value undefined is not a constructor or null
ERROR in [eslint] Failed to load plugin '@typescript-eslint' declared in '.eslintrc.json': Class extends value undefined is not a constructor or null

 

@typescript-eslint 플러그인 관련 오류는 패키지 버전의 비호환성에서 종종 발생한다.

이를 해결하기 위한 방법은

1. 패키지 업데이트

2. 캐시 삭제

3. .eslintrc.json 설정 수정

으로 순서대로 진행했다.

 

1. 패키지 업데이트

npm install @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest eslint@latest --save-dev

 

 

2. 캐시 삭제

npm cache clean --force
rm -rf node_modules package-lock.json
npm install

 

 

3. .eslintrc.json 설정

extends 필드에  plugin:@typescript-eslint/recommended   가 포함되어 있는지 확인한다. 없다면 추가!

{
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "rules": {
    // custom rules
  }
}

 

 

수정을 완료하고 패키지를 업데이트한 후 다시 eslint를 실행했다.

그랬더니

새로운 오류 발생🚨🚨🚨

ERROR in [eslint]
src/components/Modal.tsx
Line 23:11:  'ModalProps' is not defined  no-undef
Line 24:3:   'children' is not defined    no-undef
Line 25:3:   'onClose' is not defined     no-undef

 

구글링을 해보니 eslint 설정 시 환경(env)에서 node를 설정하지 않아 발생한 오류라고,,,

난 이미 설정해뒀는데 왜...;;;;;

 

 

누군가 해결 방법을 올린것을 발견해 .eslintrc.json의 env에 "jest/globals": true를 추가했다.

처음 페이지 진입 시에는 오류가 발생하지 않았지만 코드를 수정하니까 바로 오류가 발생했다;

[eslint] .eslintrc.json:
	Environment key "jest/globals" is unknown

ㄹㅈㄷ...;;;;

 

계속되는 오류에 eslint를 다시 설치하기로 결정했다!

먼저 ESLint를 초기화하고 설치했다.

npx eslint --init

 

안내 문구를 따라 선택을 완료한 후 설치를 하던 도중 또 에러가...발생했다,,,,

npm error code ERESOLVE
npm error ERESOLVE could not resolve
npm error
npm error While resolving: react-scripts@5.0.1
npm error Found: typescript@5.6.3
npm error node_modules/typescript
npm error   peer typescript@">= 2.7" from fork-ts-checker-webpack-plugin@6.5.3
npm error   node_modules/fork-ts-checker-webpack-plugin
npm error     fork-ts-checker-webpack-plugin@"^6.5.0" from react-dev-utils@12.0.1
npm error     node_modules/react-dev-utils
npm error       react-dev-utils@"^12.0.1" from react-scripts@5.0.1
npm error       node_modules/react-scripts
npm error         react-scripts@"5.0.1" from the root project
npm error   peer typescript@">=4.2.0" from ts-api-utils@1.3.0
npm error   node_modules/ts-api-utils
npm error     ts-api-utils@"^1.3.0" from @typescript-eslint/eslint-plugin@8.12.2
npm error     node_modules/@typescript-eslint/eslint-plugin
npm error       peerOptional @typescript-eslint/eslint-plugin@"^6.0.0 || ^7.0.0 || ^8.0.0" from eslint-plugin-jest@28.8.3
npm error       node_modules/eslint-plugin-jest
npm error         eslint-plugin-jest@"^28.8.3" from the root project
npm error       1 more (the root project)
npm error     ts-api-utils@"^1.3.0" from @typescript-eslint/type-utils@8.12.2
npm error     node_modules/@typescript-eslint/type-utils
npm error       @typescript-eslint/type-utils@"8.12.2" from @typescript-eslint/eslint-plugin@8.12.2
npm error       node_modules/@typescript-eslint/eslint-plugin
npm error         peerOptional @typescript-eslint/eslint-plugin@"^6.0.0 || ^7.0.0 || ^8.0.0" from eslint-plugin-jest@28.8.3
npm error         node_modules/eslint-plugin-jest
npm error         1 more (the root project)
npm error     1 more (@typescript-eslint/typescript-estree)
npm error   2 more (tsutils, the root project)
npm error
npm error Could not resolve dependency:
npm error peerOptional typescript@"^3.2.1 || ^4" from react-scripts@5.0.1
npm error node_modules/react-scripts
npm error   react-scripts@"5.0.1" from the root project
npm error
npm error Conflicting peer dependency: typescript@4.9.5
npm error node_modules/typescript
npm error   peerOptional typescript@"^3.2.1 || ^4" from react-scripts@5.0.1
npm error   node_modules/react-scripts
npm error     react-scripts@"5.0.1" from the root project
npm error
npm error Fix the upstream dependency conflict, or retry
npm error this command with --force or --legacy-peer-deps
npm error to accept an incorrect (and potentially broken) dependency resolution.
npm error
npm error
npm error For a full report see:
npm error /Users/zzionie/.npm/_logs/2024-11-08T14_27_04_215Z-eresolve-report.txt
npm error A complete log of this run can be found in: /Users/zzionie/.npm/_logs/2024-11-08T14_27_04_215Z-debug-0.log
Successfully created /Users/zzionie/Desktop/개인 프로젝트/숫자 야구/number_baseball/eslint.config.mjs file.

 

댕 큰 한숨을 내쉬고 오류를 하나씩 해결해보자...^^

 

친절하게도 오류를 하나하나 알려주기 때문에 해결할 수 있다!

ERSOLVE 오류는 주로 의존성 버전 충돌로 인해 발생한다. 위 프로젝트는 약 일년 전에 진행했기 때문에 그 사이에 버전이 많이 변한 탓인가보다,,ㅜ

 

먼저 react-scripts@5.0.1과 호환되도록 typescript의 버전을 변경한다.

npm install typescript@4.9.5

 

이후 다시 eslint 설정을 해주면.... 오류가 나지 않고 설정이 완료되었다!!!!

 

 

이후 기존 프로젝트에서 사용하던 eslint 옵션을 약간 수정했다.

1. env: 환경설정

특정 환경을 지정해 전역 변수 설정을 자동으로 적용한다.

"env": {
  "browser": true,
  "node": true,
  "es2021": true // 최신 JavaScript 문법 사용
}

 

2. extends: 기존 설정 확장

기본 설정을 확장하여 빠르게 설정을 구성한다.

"extends": [
    "eslint:recommended", // ESLint 기본 추천 설정
    "plugin:react/recommended", // React 관련 추천 설정
    "plugin:import/recommended",
    "plugin:prettier/recommended",
    "plugin:@typescript-eslint/recommended"// TypeScript 관련 추천 설정
],

여기서 기존 설정에 타입스크립트 관련 설정을 추가했다.

  • eslint: recommended -> ESLint의 기본 권장 규칙 사용
  • plugin: react/recommended -> React 관련 추천 규칙을 적용해 JSX 및 React 코드 품질을 보장
  • plugin: import/recommended -> import 플러그인의 추천 규칙을 적용해 모듈 가져오기/내보내기의 오류를 방지하고 일관성을 유지
  • plugin: prettier/recommended -> Prettier와 ESLint의 충돌을 방지하고 코드 스타일을 일관되게 유지하기 위한 Prettier 설정을 활성화
  • plugin: @typescript-eslint/recommended -> TypeScript 관련 추천 규칙을 적용해 TypeScript 문법을 더 엄격하게 관리

 

3.  plugins: 추가 플러그인

필요한 ESLint 플러그인을 추가한다. TypeScript, React 등 추가적인 기능을 위한 플러그인들을 지정할 수 있다.

"plugins": ["@typescript-eslint", "react"],

기존에 react만 설정된 플러그인에 typescript 관련 플러그인을 추가했다.

  • @typescript-eslint -> TypeScript 코드를 검사할 수 있게 하는 플러그인
  • react -> React 코드에서 사용되는 JSX 및 기타 React 관련 기능을 검사하는 플러그인

 

4. parserOptions: 파서 옵션

JavaScript 버전, 모듈 시스템 등과 관련한 옵션을 설정한다.

"parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module"
},
  • ecmaFeatures.jsx -> JSX 구문을 지원하도록 설정
  • ecmaVersion -> 최신 JavaScript버전을 사용하도록 설정 -> 최신 문법을 사용
  • sourceType -> ES모듈을 사용할 수 있도록 설정

 

5. rules: 규칙 설정

 

"rules": {
    "no-console": "off",
    "react/react-in-jsx-scope": "off",
    "react/jsx-uses-react": "off",
    "react/prop-types": "off",
    "prettier/prettier": [
      "error",
      {
        "singleQuote": true,
        "endOfLine": "auto"
      }
    ]
}
  • no-console: "off" -> 콘솔 로그를 사용하는 것을 허용. 기본적으로 ESLint는 console.log를 경고로 표시함
  • react/react-in-jsx-scope: "off" -> React 17 이상에서는 React를 JSX 범위에서 명시적으로 가져오지 않아도 되기 때문에 비활성화함
  • react/jsx-uses-react: "off" -> React가 자동으로 JSX에서 인식되기 때문에 비활성화함
  • react/prop-types: "off" -> TypeScript로 prop 타입을 관리하기때문에 PropTypes를 강제하지 않도록 비활성화함
  • prettier/prettier:
    • "error" -> prettier 규칙을 어기면 ESLint 에러로 표시
    • "singleQuote": true -> 작은 따옴표를 기본으로 사용
    • "endOfLine": "auto" -> 줄바꿈 형식을 자동으로 선택(줄바꿈 에러 방지)

 

728x90