Frontend/React

CRA + Typescript + EsLint, Prettier 프로젝트 설정하기

돌잡이개발자 2023. 8. 18. 15:29

Unsplash - Dylan Gillis

매번 프로젝트마다 빠질 수 없는 프로젝트 설정 잊어버리지 않기 위한 기록이다.

 

 

CRA + Typescript 프로젝트 설치하기

npx create-react-app my-app --template typescript

 

 

ESLint 설정하기

npm init @eslint/config


명령어 입력 후 아래 몇 가지 프로젝트 설정을 선택하면  

✔ How would you like to use ESLint? · problems
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · react
✔ Does your project use TypeScript? · Yes
✔ Where does your code run? · browser
✔ What format do you want your config file to be in? · JSON
Local ESLint installation not found.
The config that you've selected requires the following dependencies:

eslint-plugin-react@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest eslint@latest
✔ Would you like to install them now? · Yes
✔ Which package manager do you want to use? · npm



.eslintrc.json 파일이 생성된다.

// .eslintrc.json

{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended",
        "plugin:@typescript-eslint/recommended"
    ],
    "overrides": [
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "plugins": [
        "react",
        "@typescript-eslint"
    ],
    "rules": {
    }
}

 

여기에 별도로 추가하고 싶은 규칙을 rules에 추가하면 된다.

"rules": {
    "react-hooks/exhaustive-deps": "off",
    "no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars": ["error"],
    "react/react-in-jsx-scope": "off"
  }

 

 

Prettier 설정하기

npm install --save-dev --save-exact prettier

 

 

.prettierrc 파일 생성하기

// .prettierrc.json

{
  "singleQuote": true,
  "semi": true,
  "tabWidth": 2,
  "printWidth": 80,
  "trailingComma": "es5"
}

 

 

.eslintrc.json 파일에 prettier 적용하기

// .eslintrc.json

{
  // ...
 
  "extends": [
    "plugin:react/recommended",
    "prettier",
    "plugin:prettier/recommended"
  ],
  // ...
  
  "rules": {
    // ...
    "prettier/prettier": "error",
  }
  //...
}

 

 

+ 타입스크립트에 선언한 변수를 사용하지 않았을 때 에러 뜨는 현상

.eslintrc.json 파일에서 @typescript-eslint/no-unused-vars를 'error'로 설정했다.

이는 변수로 선언되었지만 실제로 호출되지 않았을 때 이를 에러로 인식한다.

이를 경고로 변경하기 위해서는 "@typescript-eslint/no-unused-vars": ["warn"] 으로 설정해야 한다.

 

또한 @typescript-eslint/no-unused-vars이 적용되기 위해서는

"extends"에 "plugin:@typescript-eslint/recommend"가 추가되어야 한다.

// .eslintrc.json

{ 
  // ...
  "extends": [
    "plugin:react/recommended",
    "prettier",
    "plugin:prettier/recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  // ...
  "rules": {
    "no-unused-vars": "off",
    // "error" -> "warn"으로 바꿔줘야 함
    "@typescript-eslint/no-unused-vars": ["warn"],
    // ...
  }
}

 

 여기까지 기본 설정 끝!

반응형