본문 바로가기

Dev-FE

[WEB] #3. tslint 로 코드 문법 설정하기

# 서론

 현업 때 angular 기반으로 프로젝트를 진행하면서 tslint로 룰셋 적용후 코드리팩토링을 수행한 경험이 딱 한번 있었다. 과제 특성 상 정부 표준 룰셋을 적용하여 진행하게되는데, 그당시는 html, script에 대한 정부 표준 룰셋이 정의되지 않아 오픈된 룰셋을 기반으로 수정하여 진행했었다. 그 이후론 기본 룰셋을 가지고 최소한으로 개발을 진행했을 뿐, eslint/tslint에 대해 깊이 생각하지 않았다. 적당히 표준만 지키면 된다고 생각했을 뿐..

 프로젝트마다 룰셋이 달랐고(언어도 달랐다), 회사마다도 다르기에 정답을 정할 순 없지만 올바른 코딩습관을 들이기 좋을 듯 하여 tslint를 적용하고 확인하는 방법을 정리하고자 한다.


#0. 실행환경

  • next.js 프로젝트 생성
    • typescript
    • styled-components
 create-next-app --ts -e with-styled-components ${PROJECT_NAME}

#1. 프로젝트 디렉토리 구조

 

...

∨ src/

  > ...

.bablerc : compile configuration

.env : environment configuration

.gitignore 

next-env.d.ts

next.config.js : next configuration

package.json : packages definition

REACME.md : project docs

styled.d.ts : styled-components declare file (custom)

tsconfig.json : typescript configuration

tslint.json : tslint configuration

yarn.lock : packages version managements

 

 

 

 

 

#2. tslint 및 룰셋 설치

- [tslint] 문서 보기

yarn add -D tslint tslint-config-airbnb tslint-react-hooks
# 또는
npm install -D tslint tslint-config-airbnb tslint-react-hooks
  • tslint-config-airbnb : 주로 많이 사용하는 문법 룰셋
  • tslint-react-hooks : react hooks 용 문법 룰셋 (react hooks 프로젝트 시 )
  • 그 외 적절한 오픈 룰셋을 사용하면 됨

#3. tslint 룰셋 적용하기

tslint --init
  • tslint --init: tslint.json 파일 생성
    • 본인은 로컬 tslint를 설치했으나, 로컬에 없어도 프로젝트 패키지에 있으면 사용가능 한 것으로 알고 있음 
# 로컬에 tslint 설치

yarn global add tslint
# 또는 
npm install -G tslint
  • tslint --init 이 안될 경우 프로젝트 최상단에 tslint.json 파일을 생성하면 됨 (구조는 #1. 프로젝트 디렉토리 구조 참고)
  • tslint.json 을 보면 아래와 유사함
# tslint.json 초기 설정
{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "rules": {
    },
    "rulesDirectory": []
    # 생략 ..
}
  • 아까 설치한 tslint-config-airbnb, tslint-react-hooks 를 추가하면 기본적으로 사용하는 룰셋이 됨
    • rules에 "react-hooks-nesting": true 추가
# tslint.json 룰셋 적용
{
    "defaultSeverity": "error",
    "extends": [
        "tslint-config-airbnb", "tslint-react-hooks"
    ],
    "rules": {
        "react-hooks-nesting": true,
    },
    "rulesDirectory": []
}
  • 이대로 사용해도 무관하며, 각 프로젝트별 특정 규약을 주고자 할 경우 rules에 추가해주면 되며, 추가옵션은 공식문서를 참고
# tslint.json
{
    "defaultSeverity": "error",
    "extends": [
        "tslint-config-airbnb", "tslint-react-hooks"
    ],
    "linterOptions": {
        "exclude": ["**/pages/_*.tsx"]
     },
    "rules": {
        "eofline": true,
        "file-name-casing": [true, { ".*": "camel-case"}],
        "import-name": false,
        "indent": [true, "spaces", 2],
        "no-trailing-whitespace": true,
        "quotemark": [true, "single", "jsx-double"],
        "react-hooks-nesting": true,
        "trailing-comma": true,
        "variable-name": {
            "options": [
                "check-format",
                "allow-leading-underscore",
                "allow-pascal-case"
            ]
        }
    },
    "rulesDirectory": []
}
  • rules
    • eofline: 파일 끝이 줄바꿈으로 끝나는지 체크
    • file-name-casting: 파일명 규칙 설정; 모든 파일 camel-case 형식으로
    • import-name: import 명 규칙 설정 제외
      • 설정하게되면 모듈에 네이밍 설정 시 고정된 규칙으로 수행해야함
      • ex1. styled-components -> styledComponents
      • ex2. react -> react 
    • indent: 구문 탭 설정
      • spaces, 2 : 탭 -> 스페이스 2로 
      • 함수의 복잡도를 제한하거나, 구문 탭을 조절하여 가독성 증가
      • space, 2 << space, 4 <<<< tab
    • no-trailing-whitespace: 후행공백 여부 체크
    • quotemark : 문자열 감싸는 따옴표 속성
      • single: 홑따옴표
      • jsx-double: jsx 파일 쌍따옴표 허용
        • pages/index.tsx 등의 head 태그를 위하여 추가
    • trailing-comma: 객체 등 후행 콤마 여부 체크
    • variable-name: 변수 명 규칙
      • check-format: 포맷 체크 옵션 ; 옵션을 커스텀 할 경우 필수
      • allow-leading-underscore: 시작부분에 밑줄허용
      • allow-pascal-case: 파스칼형식 허용
        • styled-components 변수 때문에 추가 (jsx.intrinsicElements error)
        • ex1. mapControl (X) , MapControl (O) 
        • jsx.intrinsicElements 설정을 수정하면 해당 규칙을 적용하지 않아도 됨 [참고문서보기]
  • linterOptions
    • exclude : 제외대상 

#4. 문법체크하기

아래 명령어를 이용하여 문법체크 가능

tslint -p . -c tslint.json
  • -p , --project: 대상 프로젝트
  • -c , --config: 설정파일

script 명령어로 추가하여 활용할 수 도 있음

{
  "private": true,
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start",
    "lint": "tslint -p . -c tslint.json"
  },
# ... 중량
  "devDependencies": {
    "@types/node": "^18.0.0",
    "@types/react": "^18.0.14",
    "@types/react-dom": "^18.0.5",
    "@types/styled-components": "^5.1.25",
    "tslint": "^6.1.3",
    "tslint-config-airbnb": "^5.11.2",
    "tslint-react-hooks": "^2.2.2",
    "typescript": "^4.7.4"
  }
}

 

  • 스크립트로 등록하면 프로젝트 내애서 아래와 같은 명령어로 실행 가능
yarn run lint
# 또는
npm run lint

 

후기

 개인 프로젝트를 할때도, 하나의 룰셋을 정리해서 관리하면 좋은 코드를 작성할 수 있을 듯 하다. 물론 룰셋에는 하나의 정답은 없다고 생각한다. 파트에 따라, 또는 팀에 따라서도 룰셋이 다르기때문에 협업을 한다면 서로 협의 후 적절한 룰셋을 정리하면 좋겠다. prettier를 이용하여 개발과 동시에 룰셋에 맞게 바로바로 수정할 수도 있고, husky 등을 이용하여 git commit 시 룰셋 체크를 설정할 수도 있다. 해당해서는 추 후 정리해볼 예정이다.