[ Next.js ] ESLint / Prettier (feat. typescript)

suhanLee·2022년 12월 30일
0

🌑 Ch0 - vscode 확장 플러그인 Eslint와 Prettier 설치



🌒 Ch1 - ESLint


⭐ eslint와 eslint-config-next 설치

 yarn add -D eslint eslint-config-next

⭐ npx 명령을 통해 eslint 초기 셋팅

npx eslint --init

❗ 참고

// commonjs (esm 이전) 방식 
const {useState} require('react')

// esm (ECMAScript Module) 방식
import {useState} from 'react'

commonjs방식은 안에있는 내용들을 일단 다 가져오기 때문에
최적화엔 esm 방식으로 가져오는게 좋다.


⭐ 설치 후 에러 확인

Error: Error while loading rule '@typescript-eslint/dot-notation': 
You have used a rule which requires parserServices to be generated. 
You must therefore provide a value for the "parserOptions.project" property for
@typescript-eslint/parser.

-> @typescript-eslint/parser 파싱을 위한 "parserOptions.project" 값을 제공해 달라.
-> parserOptions에 project : './tsconfig.json' 추가

  • 즉, 우리가 설정한 타입스크립트 설정 파일(tsconfig.json)을 파서에게 알려줌
module.exports = {
  env: {
    browser: true,
    es2021: true
  },
  extends: ['plugin:react/recommended', 'standard-with-typescript'],
  overrides: [],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    project: './tsconfig.json' // 추가
  },
  plugins: ['react'],
  rules: {}
};

🌓 Ch2 - Prettier


⭐ prettier 설치 및 .prettierrc.json 파일 생성

yarn add --dev --exact prettier
echo {}> .prettierrc.json

⭐ .prettierrc.json 파일 작성

{
  "singleQuote": true,
  "semi": true, 
  "useTabs": true,
  "tabWidth": 2,
  "printWidth": 80,
  "bracketSpacing": true,
  "arrowParens": "avoid",
  "trailingComma": "none",
  "endOfLine": "auto"
}

📢 의미

singleQuote: true, //  "" -> ''
semi: true, // alert('1') -> alert('1');
useTabs: true, //공백 대신 탭을 사용해서 들여 씀
tabWidth: 2, //탭 간격( 공백 수2 )
printWidth: 80, //80칸이 넘어가면 개행
bracketSpacing: true, //{foo: bar} -> { foo: bar }
arrowParens: 'avoid', // always : (x) => x, avoid : x => x
trailingComma: 'all', //객체에서 후행 쉼표 사용
endOfLine: 'auto', // 줄끝 라인 맞추기

⭐ eslint-config-prettier, eslint-plugin-prettier 설치

yarn add -D eslint-plugin-prettier eslint-config-prettier
패키지설명
eslint-config-prettierESLint 규칙에서 Pretter 규칙과 충돌하는 규칙들을 OFF 시키는 역할
eslint-plugin-prettierPrettier 규칙들을 ESLint 규칙에 추가하는 패키지.
eslint --fix 만 실행해줘도 prettier --write를 사용할 필요 없이 prettier까지 적용시켜준다

⭐ .eslintrc.js 최종 확인

module.exports = {
  env: {
    browser: true,
    es2021: true
  },
  extends: ['plugin:react/recommended', 'standard-with-typescript', 'prettier'], // 추가 ('prettier' 충돌방지 eslint, prettier)
  overrides: [],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    project: './tsconfig.json' //추가
    //project: '**/tsconfig.json' // vscode내 여러 프로젝트 한번에 열었을 때
  },
  plugins: ['react'],
  rules: {}
};

🌔 Ch3 - VScode


방법 1

⭐ 포맷팅 자동 저장을 위한 vscode 설정

현재 열려있는 vscode 프로젝트 폴더 기준으로 최상단.vscode 폴더를 생성하고
settings.json 파일을 생성한다.


settings.json 내용 추가

{
  "editor.formatOnSave": true, // 파일 저장 시 자동 포맷팅
  "editor.defaultFormatter": "esbenp.prettier-vscode" // 기본 포맷터
}
{
	"editor.codeActionsOnSave": {
		"source.fixAll.eslint": true
	},
	"editor.tabSize": 2
}

방법 2 vscode 설정에서 직접 선택


🌕 Ch4 - 확인


🍻 코드 포맷팅 확인

파일 저장 시 셋팅한 포맷팅이 적용 된다.


🍻 eslint 확인

.eslintrc.js에서 확장으로 가져온 플러그인 plugin:react/recommended 규칙에 따른 에러 방출

  • React 가 선언 되어 있어야 한다는 내용

  • 리턴 타입이 JSX인 function의 리턴 타입을 명시하라는 내용


추가 🔨

이런 ESlint 에러에 대한 모든 규칙을 지킬 필요는 없다.
팀 프로젝트 특성에 맞지 않는 룰들을 제외 시킬 수도 있다.

module.exports = {
	env: {
		browser: true,
		es2021: true
	},
	extends: ['plugin:react/recommended', 'standard-with-typescript', 'prettier'],
	overrides: [],
	parserOptions: {
		ecmaVersion: 'latest',
		sourceType: 'module',
		project: './tsconfig.json'
	},
	plugins: ['react'],
	rules: {
      	'react/self-closing-comp': [ //셀프클로징 추가
			'error',
			{
				component: true,
				html: true
			}
		],
		'react/react-in-jsx-scope': 'off', // 추가 jsx파일 내 React 선언 제외
		'@typescript-eslint/explicit-function-return-type': 'off', // 추가 리턴타입 jsx 제외
		'@typescript-eslint/strict-boolean-expressions': 'off', // truthy, falsy한 값을 엄격하게 체크 제외
		'@typescript-eslint/no-misused-promises': 'off', // 추가 Promise return 타입에 void가 예상되는 에러 규칙 제외
      // 내가 프로미스를 사용하는 함수타입이 리턴이 없어서  () => void로 정의해 놓았는데
      // onMyClickHandler : () => Promise<void>로 바꿔줘야 한다는 경고
      // 바꿔주게 되면 onMyClickHandler를 onClick={onMyClickHandler}로 사용하는 jsx에서 
      // 바로 promise<void>를 리턴할 수 없다는 문제가 나옴
      // 그럼 다시 onClick={() => onMyClickHandler}로 함수로 감싸줘야 하는 번거로움이 있음 ,, 그래서 제외
		'@typescript-eslint/triple-slash-reference': 'off' // 추가 declare typescript 파일 ///<reference /> 삼중 슬래시 지시자에서 ///사용하지 말라는 경고가 나오기 때문에 규칙 제외
      
      //기타
      //@typescript-eslint/no-floating-promises
      // router.push()할때 뒤에 .catch를 붙여 항상 에러를 캐치하게 적용 할지..
      //@typescript-eslint/restrict-template-expressions
  	  // 템플릿 리터럴 방식에서 undefined가 될만한 요소 체크
      // `템${undefined ?? ""}터럴`과 같이 nullish를 사용하던지 옵션을 끄던지.. 고민
	}
};

eslint 규칙에 어긋난 파일 목록 보기

npx eslint .

eslint 규칙에서 제외할 파일 설정

백엔드 graphql에서 api에 대한 타입 명세를 generate한 ts파일

이건 내가 작성한게 아니기 때문에 무시 하겠다는 옵션을 추가해줬다

.eslintignore 생성

0개의 댓글