Frontend/React

React ESLint + Prettier 적용하기

freestrokes 2022. 2. 19. 23:46
반응형

 

React ESLint + Prettier 적용하기

 

React에 ESLint와 Prettier를 적용하는 방법에 대해 알아보겠습니다.

 

 

 

1. ESLint 설치


ESLint는 JavaScript 코드를 분석하여 문법 검사를 지원하고 런타임 이전에 오류를 찾아주는 도구입니다. 커스터마이징이 쉽고 확장성이 뛰어나다는 장점이 있습니다. 좀 더 편리하게 사용하기 위해 airbnb 또는 google의 스타일 가이드를 많이 사용하기도 합니다.

 

다음 명령어를 실행하여 ESLint를 설치해줍니다.

$ yarn add eslint

 

설정에 사용할 plugin과 parser를 다음과 같이 설치해줍니다.

$ yarn add eslint-plugin-react @typescript-eslint/parser @typescript-eslint/eslint-plugin

 

다음으로 ESLint 설정을 위해 .eslintrc.js 파일을 다음과 같이 작성해줍니다. 주요 설정들에 대해 간단하게 설명하면 다음과 같습니다.

 

  • parser
    구문 분석을 위해 사용하는 parser 설정.
  • parserOptions
    JavaScript 언어 옵션 설정.
  • env
    browser, node와 같은 사전 정의된 전역변수 사용 설정.
    document, window와 같은 브라우저 내장 객체 사용시 ESLint 에러가 없도록 설정.
  • extends
    추가한 plugin에서 사용할 규칙을 설정.
  • rules
    프로젝트에 사용할 규칙을 설정.
    규칙에 추가 옵션이 있는 경우 배열을 사용하여 설정 가능.
    off 또는 0 사용시 규칙을 사용하지 않음.
    warn 또는 1 사용시 규칙을 경고로 사용.
    error 또는 2 사용시 규칙을 오류로 사용.

rules에는 다음 링크를 참고하여 필요한 설정을 추가해줍니다.

 

List of available rules

✓no-unreachabledisallow unreachable code after `return`, `throw`, `continue`, and `break` statements

eslint.org

module.exports = {
  parser: "@typescript-eslint/parser",
  root: true,
  env: {
    browser: true,
    commonjs: true,
    es6: true,
    jest: true
  },
  extends: [
    "plugin:@typescript-eslint/recommended",
    "plugin:import/errors",
    "plugin:import/warnings",
    "plugin:import/typescript",
    "plugin:react/recommended",
    "plugin:prettier/recommended",
    "prettier"
  ],
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: "module",
    ecmaFeatures: {
      "jsx": true
    }
  },
  rules: {
    "indent": "off",
    "camelcase": "off",
    "semi": "off",
    "quotes": "off",
    "no-shadow": "off",
    "no-use-before-define": "off",
    "no-unused-vars": "off",
    "no-console": "off",
    "no-magic-numbers": "off",
    "no-redeclare": "off",
    "no-array-constructor": "off",
    "no-dupe-class-members": "off",
    "no-extra-semi": "off",
    "no-empty-function": "off",
    "linebreak-style": "off",
    "prettier/prettier": "off",
    "jsx-a11y/no-noninteractive-element-interactions": "off",
    "import/extensions": "off",
    "import/no-unresolved": "off",
    "import/no-extraneous-dependencies": "off",
    "import/prefer-default-export": "off",
    "import/no-named-as-default": "off",
    /* react options */
    "react/prop-types": "off",
    "react/display-name": "off",
    "react/react-in-jsx-scope": "off",
    "react/destructuring-assignment": "off",
    "react/no-array-index-key": "off",
    "react/jsx-filename-extension": [2, { extensions: [".js", ".jsx", ".ts", ".tsx"] }],
    "react/function-component-definition": 2,
    /* typescript-eslint options */
    "@typescript-eslint/no-empty-interface": "warn",
    "@typescript-eslint/adjacent-overload-signatures": "warn",
    "@typescript-eslint/no-dupe-class-members": "warn",
    "@typescript-eslint/no-misused-new": "warn",
    "@typescript-eslint/no-redeclare": "warn",
    "@typescript-eslint/no-array-constructor": "warn",
    "@typescript-eslint/no-namespace": "warn",
    "@typescript-eslint/no-var-requires": "warn",
    "@typescript-eslint/prefer-namespace-keyword": "warn",
    "@typescript-eslint/no-shadow": "off",
    "@typescript-eslint/no-empty-function": "off",
    "@typescript-eslint/type-annotation-spacing": "off",
    "@typescript-eslint/no-extra-semi": "off",
    "@typescript-eslint/member-ordering": "off",
    "@typescript-eslint/no-inferrable-types": "off",
    "@typescript-eslint/no-use-before-define": "off",
    "@typescript-eslint/no-non-null-asserted-optional-chain": "off",
    "@typescript-eslint/no-non-null-assertion": "off",
    "@typescript-eslint/no-unused-vars": "off",
    "@typescript-eslint/no-explicit-any": "off",
    "@typescript-eslint/semi": "off",
    "@typescript-eslint/naming-convention": "off",
    "@typescript-eslint/indent": "off",
    "@typescript-eslint/member-delimiter-style": "off",
    "@typescript-eslint/quotes": "off",,
    "@typescript-eslint/consistent-type-assertions": "off",
    "@typescript-eslint/triple-slash-reference": "warn",
    "@typescript-eslint/no-magic-numbers": "off"
    },
    ignorePatterns: ["node_modules/"],
    settings: {
    react: {
      version: "detect"
    }
  }
};

 

 

 

2. Prettier 설치


Prettier는 정해진 규칙에 따라 코드 스타일을 정리해주는 도구입니다. 다음 명령어를 실행하여 Prettier를 설치해줍니다.

$ yarn add prettier

 

앞서 설치한 ESLint와의 충돌을 방지하기 위해 eslint-config-prettier, eslint-plugin-prettier를 설치해줍니다.

$ yarn add eslint-config-prettier eslint-plugin-prettier

 

  • eslint-config-prettier
    Prettier를 ESlint의 플러그인으로 추가하여 Prettier의 오류를 ESLint에서 출력하도록 설정.
    ESLint의 포맷이 아닌 Prettier의 포맷을 사용하도록 설정.
  • eslint-plugin-prettier
    ESLint의 설정중에서 Prettier와 충돌하는 설정을 비활성화.

설치가 완료되면 .prettierrc.js 파일을 생성하고 다음과 같이 작성해줍니다.

module.exports = {
  "singleQuote": true,
  "semi": true,
  "useTabs": false,
  "tabWidth": 2,
  "trailingComma": "all",
  "printWidth": 120,
  "arrowParens": "always"
};

 

다음으로 .eslintrc.js 파일에서 extends에  prettier 설정을 추가해줍니다.

module.exports = {
  ...
  "extends": [
    ...
    "prettier",
    "prettier/@typescript-eslint",
    "plugin:prettier/recommended"
  ],
  ...
};

 

마지막으로 package.json 파일을 수정해줍니다. eslintConfig 프로퍼티의 extends에 prettier를 추가해주고 scripts 프로퍼티에 lint, prettier 옵션을 추가해줍니다.

{
  ...
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest",
      "prettier"
    ]
  },
  ...
  "scripts": {
    ...
    "prettier": "prettier --write --config ./.prettierrc \"**/*.{ts,tsx}\"",
    "lint": "eslint './src/**/*.{ts,tsx}'",
    "lint:fix": "eslint --fix './src/**/*.{ts,tsx}'"
  },
  ...
}

 

이상으로 React에 ESLint와 Prettier를 적용하는 방법에 대해 알아봤습니다.

 

 

※ Reference

 

 

반응형