본문 바로가기
Programming/Node.js

react-create-app으로 만든 typescript 프로젝트에 eslint 적용하기

by 신규하 2020. 9. 15.

적용해 보면서 하도 고생해서 정리해 봅니다.

Create-react-app

먼저 create-react-app를 통해서 프로젝트를 생성합니다.

$ yarn create react-app my-app-name --template=typescript
$ cd my-app-name

 

Eslint

생성된 프로젝트 폴더로 이동한 후 eslint를 설치 해 줍니다.

$ yarn add -D eslint

이게 yarn eslint --init을 통해서 eslint를 설정해 줍니다.

$ yarn eslint --init
? 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

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

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

? Does your project use TypeScript? » No / Yes

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

? How would you like to define a style for your project? ...
> Use a popular style guide
  Answer questions about your style
  Inspect your JavaScript file(s)

? Which style guide do you want to follow? ...
> Airbnb: https://github.com/airbnb/javascript
  Standard: https://github.com/standard/standard
  Google: https://github.com/google/eslint-config-google

? What format do you want your config file to be in? ...
  JavaScript
  YAML
> JSON

Checking peerDependencies of eslint-config-airbnb@latest
The config that you've selected requires the following dependencies:

eslint-plugin-react@^7.20.0 @typescript-eslint/eslint-plugin@latest eslint-config-airbnb@latest eslint@^5.16.0 || ^6.8.0 || ^7.2.0 eslint-plugin-import@^2.21.2 eslint-plugin-jsx-a11y@^6.3.0 eslint-plugin-react-hooks@^4 || ^3 || ^2.3.0 || ^1.7.0 @typescript-eslint/parser@latest
? Would you like to install them now with npm? » No / Yes

옵션은 위와 같이 설치해 줍니다.

그런데 마지막에 필요한 패키지가 있다고 설치 하라고 하는데, 그걸 설치하면 react-scripts가 실행이 되지 않는 문제가 현재(2020년 9월 15일) 발생합니다. 나중에 고쳐 질 것 으로 보이지만 지금은 문제가 발생합니다. 그래서 eslintrc.json만 작성하고 설치는 No를 선택합니다.

그리고 아래의 명령어로 설치해 줍니다. 위에꺼대로 설치 해서 잘 된다면 아래꺼는 하실 필요가 없습니다.

yarn add eslint-plugin-react@^7.19.0 @typescript-eslint/eslint-plugin@ˆ2.28.0 eslint-config-airbnb@latest eslint@^6.8.0 eslint-plugin-import@^2.20.1 eslint-plugin-jsx-a11y@^6.2.3 eslint-plugin-react-hooks@^2.5.0 @typescript-eslint/parser@latest -D

 

그리고 리엑트에서 타입 스크립트의 import를 이해 eslint-import-resolver-typescript 패키지가 필요 합니다. 아래와 같이 설치해 줍니다.

yarn add -D eslint-plugin-react@^7.19.0 @typescript-eslint/eslint-plugin@ˆ2.28.0 eslint-config-airbnb@latest eslint@^6.8.0 eslint-plugin-import@^2.20.1 eslint-plugin-jsx-a11y@^6.2.3 eslint-plugin-react-hooks@^2.5.0 @typescript-eslint/parser@latest

@typescript-eslint/eslint-plugin 패키지를 고르라고 나오는데 여기서는 4.1.1을 골랐습니다. 

그리고, eslint에서 제외할 폴더를 지정하기 위해서 .eslintignore 파일을 만들고 아래와 같이 넣어 줍니다.

**/*.js
node_modules
build

그리고 아래와 같이 eslint를 실행해 봅니다.

yarn eslint ./src/**/*.tsx

그러면 es2021을 모르겠다고 나옵니다. eslint 버전을 낮춰서 설치를 해서 생긴 문제 입니다. 이건 .eslintrc.json 파일의 env 항목에서 es2021을 es6로 변경해 주면 됩니다.

그리고 다시 실행하면 eslint에 맞지 않는 파일들이 쭈욱~ 나오는 것을 확인 하 수 있습니다. eslint가 정상적으로 설치 된 것을 확인 할 수 있습니다.

요즘 react에서 hooks를 안 쓰면 react가 아니죠. eslint-plugin-react-hooks를 설치해 줍니다. 그리고 추가로 jest용 eslint도 추가해 줍니다.

$ yarn add -D eslint-plugin-react-hooks eslint-plugin-jest

그리고 eslintrc.json 파일에 아래와 같이 추가해 주면 됩니다.

{
  "plugins": [
    // ...
    "jest",
    "react-hooks"
  ],
  "rules": {
    // ...
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn"
  }
}

Prettier

이제 vscode에서 원활한 사용을 위해서 prettier를 설치해 줍니다. vscode의 prettier 확장은 꼭~ 설치해 주세요.. 정말 보물 같은 확장입니다.

그러면 아래와 같이 prettier관련 패키지를 설치해 줍니다.

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

 

그리고 .eslintrc.json 파일을 아래와 같이 넣어 줍니다.

{
  "env": {
    "browser": true,
    "es6": true,
    "jest": true
  },
  "extends": [
    "plugin:react/recommended",
    "airbnb",
    "prettier/@typescript-eslint",
    "plugin:prettier/recommended",
    "prettier/react"
  ],
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "plugins": [
    "jest",
    "react",
    "@typescript-eslint",
    "prettier",
    "react-hooks"
  ],
  "rules": {
    "prettier/prettier": [
      "error"
    ],
    "no-console": "off",
    "react/jsx-filename-extension": [
      1,
      {
        "extensions": [
          ".js",
          ".jsx",
          ".ts",
          ".tsx"
        ]
      }
    ],
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "js": "never",
        "jsx": "never",
        "ts": "never",
        "tsx": "never",
        "json": "never"
      }
    ],
    "react/jsx-props-no-spreading": "off",
    "jsx-a11y/click-events-have-key-events": 0,
    "jsx-a11y/no-static-element-interactions": 0,
    "no-plusplus": "off",
    "import/prefer-default-export": "off",
    "@typescript-eslint/no-unused-vars": "warn",
    "no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars-experimental": "warn",
    "react/js-no-target-blank": "off",
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn",
    "@typescript-eslint/explicit-function-return-type": "off",
    "no-use-before-define": ["off", { "variables": false }]
  },
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [
          ".js",
          ".jsx",
          ".ts",
          ".tsx"
        ]
      }
    }
  }
}

위 내용은 제가 사용하면서 정리한 내용이라서 사용자의 편의에 따라서 수정해서 사용하시면 됩니다.

그리고, .prettierrc 파일을 만들고 아래와 같이 입력해 줍니다.

{
  "endOfLine": "auto",
  "parser": "typescript",
  "printWidth": 100,
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "useTabs": false
}

대부분은 prettier의 기본값으로 사용하고 있으면 특별히 변경해서 사용하는 것만 기록을 해 뒀습니다. 기본 값은 아래 주소에서 확인 하시면 됩니다. 

prettier.io/docs/en/options.html

 

Prettier · Opinionated Code Formatter

Opinionated Code Formatter

prettier.io

이제 prettier에서 제외로 할 파일 또는 폴더를 지정해 줍니다.

.pre.prettierignore 파일을 만들고 아래와 같이 입력해 줍니다.

dist
build
package.json

 

VSCODE

이제 마지막으로 vscode에서 파일을 저장 할 때 자동으로 포맷을 할 수 있도록 설정해 줍니다.

.vscode 폴더를 만들고 settgins.json 파일에 아래와 같이 입력해 줍니다.

파일명 : .vscode/settings.json

{
  "[typescript]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescriptreact]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javscript]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

 

여기까지 하시면 eslint 설정은 거의 완료 됩니다.

이제 열코딩을 하시면 됩니다~

그리고, 뭔가 이상하면 하거나 불편하다면 .eslintrc.json 또는 .prettierrc 파일을 수정해 나가면서 나한테 맞는 lint 값을 찾아 가시면 됩니다.

위 내용이 적용된 소스를 아래 주소에 있습니다.

github.com/gyuha/react-create-app-eslint

 

gyuha/react-create-app-eslint

Contribute to gyuha/react-create-app-eslint development by creating an account on GitHub.

github.com

 

댓글