Coding Rule 설정 ESlint & Prettier

homewiz·2023년 11월 13일
0

CRA create react app

목록 보기
3/6
post-thumbnail

개요

협업 프로젝트시에 코딩룰이 적용된 소스는 인체에 유익 하다는 전제 하에 강제하는 방법을 알아 본다.

Is prettier ?

MIT license를 가진 code formatter 모듈입니다. Code format이란 줄 바꿈, 줄간격, 괄호의 위치 등 여러 가지 Style을 의미하며, Prettier는 이런 code style을 자동적으로 정리해 줍니다.

Is eslint?

javascript 정적 분석 도구

ESLint란? ECMAScript Lint의 줄임말로, javascript의 표준을 다루는 협회가 바로 ECMA입니다. Lint는 유닉스 시절에 정적코드 분석 프로그램인 'Linter"에서 따온 이름입니다.

Install Plugin

full command 
yarn add -D eslint prettier eslint-plugin-import eslint-plugin-prettier eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y eslint-config-prettier

: 1. eslint: Javascript 정적 분석 도구
yarn add --dev eslint

: 2. prettier: auto code formatter module 
yarn add --dev prettier

: 3. ES6import, export 구문 지원
yarn add --dev eslint-plugin-import

: 4. eslint와 prettier간 충돌방지 플러그인
yarn add eslint-plugin-prettier --dev

: 5. for react 구문
yarn add eslint-plugin-react --dev
yarn add eslint-plugin-react-hooks --dev

: 6. for jsx(xml) 정적 분석
yarn add eslint-plugin-jsx-a11y --dev

: 7. prettier 설정
yarn add --dev eslint-config-prettier

Prettier config

file: root/.prettierrc

{
  "endOfLine": "auto",
  "semi": true,
  "singleQuote": false,
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "arrowParens": "avoid",
  "bracketSpacing": false,
  "htmlWhitespaceSensitivity": "css",
  "jsxBracketSameLine": false,
  "jsxSingleQuote": false,
  "proseWrap": "preserve",
  "quoteProps": "as-needed",
  "trailingComma": "none",
  "vueIndentScriptAndStyle": false,
  "filepath": "",
  "requirePragma": false,
  "insertPragma": false,
  "overrides": [
    {
      "files": "*.json",
      "options": { "printWidth": 80, "trailingComma": "none" }
    },
    {
      "files": "*.prettierrc",
      "options": { "printWidth": 80, "trailingComma": "none" }
    }
  ]
}

아래 사이트를 통해 룰 설정을 미리 체험 할 수 있다.
https://prettier.io/playground/

eslint confing

yarn eslint --init
yarn run v1.22.19
$ C:\Projects\Sources\react-components\node_modules\.bin\eslint --init
You can also run this command directly using '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? · No / Yes
√ Where does your code run? · browser
√ What format do you want your config file to be in? · JSON
The config that you've selected requires the following dependencies:

eslint-plugin-react@latest
√ Would you like to install them now? · No / Yes
√ Which package manager do you want to use? · yarn
Installing eslint-plugin-react@latest
  • init 명령어를 수행후 설정 항목을 응답하면 eslintrc.json 파일이 생성
  • 본인은 .eslintrc 로 파일명을 수정 하여 사용한다.\
{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": ["eslint:recommended", "plugin:react/recommended"],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["react"],
  "rules": {}
}
  • 사전에 설치한 plugin을 extends에 추가 해준다.
    package.json
"devDependencies": {
    "@craco/craco": "^7.1.0",
    "eslint": "^8.53.0",
    "eslint-config-prettier": "^9.0.0",
    "eslint-plugin-jsx-a11y": "^6.8.0",
    "eslint-plugin-prettier": "^5.0.1",
    "eslint-plugin-react": "^7.33.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "prettier": "^3.0.3"
  }

.eslintrc 추가

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "prettier",
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:jsx-a11y/recommended",
    "plugin:prettier/recommended",
    "plugin:react-hooks/recommended"
  ],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["react"],
  "rules": {}
}

문법 검사 테스트

  • yarn start를 통해 실행
  • App.js 소스에 에러 구문을 추가 해본다.

function App() {
  const a = 10;
  asdfasdfsafas;
  ...
  • 브라우저와 vscode 터미널에 에러가 출력 된다.
[eslint]
src\App.js
  Line 6:9:  'a' is assigned a value but never used  no-unused-vars
  Line 7:3:  'asdfasdfsafas' is not defined          no-undef

Search for the keywords to learn more about each error.
ERROR in [eslint]
src\App.js
  Line 6:9:  'a' is assigned a value but never used  no-unused-vars
  Line 7:3:  'asdfasdfsafas' is not defined          no-undef

Search for the keywords to learn more about each error.

webpack compiled with 1 error

VSCode Extention ESLint

  • complie 전 코딩단계에서도 문법 오류 힌트가 발생하게 해준다.
  • Ctrl + Shift + X를 통해 Extention으로 이동
  • 검색 창에 ESLint 검색 후 설치
  • ctrl + shift + p > reload window 재실행
  • App.js 아래와 같이 오류 구문에 밑줄 발생

VSCode Extention Prettier

  • 세미콜론, 줄간격, 내려쓰기등 간단한 규칙을 자동으로 수정 해주는 툴
  • Extention > Prettier 검색 후 Prettier-code formatter 설치

  • setting.json
    1. open setting json (ctrl + shift + p)
    2. input "open user setting"
    3. add line ------
      "editor.defaultFormatter": "esbenp.prettier-vscode",
      "editor.formatOnSave": true,
      "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
      }

  • set settings
  1. open setting(ctrl + ,)
  2. search "default formatter" > select Prettier-Code fromatter
  3. search "FormatOnSave" > check box: true
  • 저장시 변경 기능을 사용 하지 않을 경우 shift + alt + f 키를 통해 자동 수정 이용 가능

  • App.js에서 아래와 같이 시작 p 태그 라인이 맞지 않는 경우
<img src={logo} className="App-logo" alt="logo" />
                  <p>
		Edit <code>src/App.js</code> and save to reload.
	</p>

shift + alt + f를 누르면 아래와 같이 자동으로 잡아 준다.

<img src={logo} className="App-logo" alt="logo" />
	<p>
		Edit <code>src/App.js</code> and save to reload.
	</p>

0개의 댓글

관련 채용 정보