본문 바로가기
📍 Front-End/🜸 TypeScript

React + Typescript + ESLint + prettier 환경 구성하기 (2022. 5. 29 기준)

by 예리Yelee 2022. 5. 29.
반응형

📍 패키지 매니저로 yarn을 이용했습니다.
📍 Mac OS 기반으로 설치한 가이드입니다.


1. 프로젝트 생성

yarn create react-app template  --template typescript
// yarn create react-app ${프로젝트명} --template typescript

--template typescript : typescript 모드로 프로젝트를 생성해준다는 명령어 옵션입니다!

2. ESLint 설치

yarn add -D eslint

 

3. ESLint의 config 파일을 초기화

$ yarn eslint --init

You can also run this command directly using 'npm init @eslint/config'.
Need to install the following packages:
  @eslint/create-config
Ok to proceed? (y)

$ y

 

init 명령어를 입력하면 @eslint/create-config 패키지를 설치하라는 안내가 뜬다.
y를 눌러 설치를 진행한다

? How would you like to use ESLint? … 
  To check syntax only
❯ To check syntax and find problems
  To check syntax, find problems, and enforce code style

prettier를 통해 코트 스타일을 포맷팅 할 예정이므로
두 번째 탭('To check syntax and find problems')에서 엔터를 누른다.
ESLint로는 코드 스타일을 제외한 문법적 오류만 잡아낸다.

? What type of modules does your project use? … 
❯ JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these

React는 자바스크립트 모듈 타입을 이용하므로 첫 번째 탭에서 엔터!

? Which framework does your project use? … 
❯ React
  Vue.js
  None of these

리액트 프로젝트이므로 첫 번째 탭에서 엔터!

? Does your project use TypeScript? › No / Yes

타입 스크립트 기반 프로젝트를 구성하는 중이니 Yes! 탭에서 엔터!

? Where does your code run? …  (Press <space> to select, <a> to toggle all, <i> to invert selection)
✔ Browser
  Node

 

Browser에서 엔터!

? What format do you want your config file to be in? … 
❯ JavaScript
  YAML
  JSON

config 파일을 어떤 포맷으로 할지는 각자 니즈에 맞게 선택하면 된다
저는 JSON에서 엔터!

eslint-plugin-react@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
? Would you like to install them now? › No / Yes

 

 

필요한 dependancy 설치 여부 -> Yes!

? Which package manager do you want to use? … 
  npm
❯ yarn
  pnpm

 

 

패키지 매니저를 yarn으로 사용하고 있으므로 yarn에서 엔터!

프로젝트를 열어보면 아래와 같은. eslintrc.json 파일이 생성된 것을 확인할 수 있습니다

 

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

 

4. prettier 설치 

yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

 

5. .eslintrc.json 파일 수정

 

prettier와 eslint를 같이 사용하기 위해서 eslintrc 파일을 수정해야 합니다

{
    ...code, 
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended",
        "plugin:@typescript-eslint/recommended",
        "prettier" // 추가!
    ],
    ...code, 
}


그다음 ESLint에서 가장 중요한 rules를 설정해야 됩니다
개발해나가면서 더 추가되겠지만 기본적으로 아래와 같이 설정했습니다

{
    ...code, 
    "rules": [
        "react/react-in-jsx-scope": "off",
        "spaced-comment": "error",
        "quotes": ["error", "single"],
        "no-duplicate-imports": "error"
    ],
    ...code, 
}

 

rules에 관한 옵션을 자세히 알고 싶으면 여기를 클릭해주세요

지금까지 설치한 플러그인을 사용하기 위해 eslintrc.json 파일에서 플로그인 부분도 수정을 해야 됩니다

{
    ...code, 
    "plugins": [
        "react",
        "react-hooks",
        "@typescript-eslint",
        "prettier"
    ],
    ...code, 
}

 

마지막으로 setting키를 추가!

{
   // ...code,
  "settings": { 
    "import/parsers": {
      "@typescript-eslint/parser": [".ts", ".tsx", ".js"] 
    }, 
    "import/resolver": { 
      "typescript": "./tsconfig.json" 
    }
  }
   // ...code,
}

 

6. .prettierrc 파일 생성

{
    "semi": true, // 세미콜론(;) 사용 여부
    "tabWidth": 2, // 탭 너비
    "printWidth": 80, // 자동 줄 바꿈이 되는 길이
    "singleQuote": true, // 싱클 쿼테이션('') 적용 여부
    "trailingComma": "none", // 여러줄일때 후행 콤마 방식
    "jsxSingleQuote": true, // JSX에 싱글 퀘테이션 사용 여부
  }

prettier의 옵션에 대해 더 자세히 알고 싶으면 여기를 클릭해주세요

 

7. package.json 파일 수정

거의 다 왔습니다!
아래와 같이 package.json 파일의 스크립트를 수정해주세요

{
  //...code,
  "scripts": {
    //...code,
    "lint": "eslint src/**/*.{js,jsx,ts,tsx,json}",
    "lint:fix": "eslint --fix 'src/**/*.{js,jsx,ts,tsx,json}'",
    "prettier": "prettier --write 'src/**/*.{js,jsx,ts,tsx,css,md,json}' --config ./.prettierrc"
  }
  //...code
}

lint는 eslint로 문제를 발견하고
lint fix는 eslint로 문제를 발견해서 고치기까지
그리고 prettier은 prettier로 코드 스타일을 고치는데 도움을 줄 명령줄입니다

🎉 여기까지 환경 구성이 완료되었습니다
잘 되는지 확인을 해봐야겠죠?

yarn start로 애플리케이션을 실행해보니
아래와 같이 eslint에 의해 코드상 WARNING이 발생하는 것을 확인할 수 있습니다

 

그런데 저장 버튼을 눌러도 Prettier가 작동을 안 하는 것 같네요
어찌 된 걸까,,,,,,,🫠

혹시 위 방식대로 차근차근 따라 했는데 Prettier로 자동 formatting 안 되는 분 계시면
여길 봐주세요~~~~~~~~~~~~~~~~🎤

 

저의 경우 얼마 전 새로 구매한 맥북이다 보니 VSCode에 설정이 아무것도 안되어 있는 게 문제였습니다
Code -> Preferences -> Setting (단축키 : command + ,)로 들어가 주세요

 

그다음 format on save를 검색하면 아래와 같은 탭이 뜨는데
여기서 체크가 안되어있다면 꼭 체크해주셔야 됩니다.

 

또 수정해야 될 부분은 Settings의 우측 상단 아이콘을 클릭하면
setting.json 파일이 열립니다
아이콘을 찾기 힘들다면 command + shift + P  단축키를 쓴 다음
settings.json 파일을 검색해서 들어가 주세요



그리고 이 json 파일에 자동 포맷팅을 위한 값을 입력해야 됩니다

{
    "[typescript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[typescriptreact]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "editor.formatOnSave": true // format on save에 체크되어 있으면 자동으로 추가 되는 키값
}

 

자 이제 파일에서 코드를 작성한 다음 저장버튼을 눌러보세요!
prettierrc에서 정의한 대로 자동 포맷팅이 되는지 확인 가능,,, 하시죠? 제발,, 그러길 ^^



도움이 되었다면 하트와 광고 한 번씩 누르고 가주세요


 

반응형

댓글