개발

[React/Vite] ESLint 설정하기

hayeonn 2023. 5. 4. 15:48
반응형

초기 환경설정에이어 이제 ESlint 설정을 해보려고 한다.

 

1. ESLint 구성 파일

ESlint 구성 파일을 npm 초기화 명령을 사용해 생성한다.

npm init @eslint/config

그러면 파일구조에 .eslintrc.cjs 라는 파일이 생성된다.

 

2. ESLint 린팅 제외 파일

특정 파일 또는 디렉토리의 경우 린팅을 수행하지 않도록 ESlint에 지시할 수 있다.

.eslintignore 파일을 생성하고 린팅(linting) 검사에서 제외할 디렉토리를 작성하자.

 

.eslintignore

build
coverage
dist

 

3. ESLint 플러그인 구성

ESLint가 제공하는 다양한 플러그인 중 React 개발과 관련된 항목 구성에 대해 살펴보자.

 

1) eslint-plugin-react

ESLint 구성 파일에 settings 구성 항목을 추가한 후 React 버전을 감지할 수 있도록 설정한다.

이어서 extends 확장 배열에 react/jsx-runtime 플로그인 항목을 추가 작성한다.

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
	settings: {
    react: {
      version: 'detect',
    },
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react/jsx-runtime',
  ],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: ['react'],
  rules: {
		'no-console': 'warn',
		'react/prop-types': 'off',
		'react/button-has-type': 'warn',
		'react/self-closing-comp': [
			'warn',
			{
				component: true,
				html: false
			}
		],
		'react/jsx-sort-props': [
		  'warn',
		  {
		    shorthandFirst: true,
		    callbacksLast: true,
		    noSortAlphabetically: false,
		    reservedFirst: true,
				multiline: 'last',
		  },
		],
	},
};

 

2) eslint-plugin-react-hooks

ESLint 플러그인 eslint-plugin-react-hooks 패키지를 개발 종속성 모듈로 설치한다.

npm i -D eslint-plugin-react-hooks
module.exports = {
	// ...
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react/jsx-runtime',
	'plugin:import/recommended',
    'plugin:react-hooks/recommended',
  ],
  plugins: [
		'react', 
		'import',
		'react-hooks'
	],
	rules: [
		'react-hooks/rules-of-hooks': 'error',
		'react-hooks/exhaustive-deps': 'warn',
		// ...
	],
};

 

 

3) eslint-plugin-jsx-a11y

npm i -D eslint-plugin-jsx-a11y
module.exports = {
	// ...
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react/jsx-runtime',
	'plugin:import/recommended',
    'plugin:react-hooks/recommended',
	'plugin:jsx-a11y/recommended',
  ],
  plugins: [
		'react', 
		'import',
		'react-hooks',
		'jsx-a11y',
	],
	rules: [
		// ...
		'jsx-a11y/anchor-has-content': [
      'warn',
      {
        components: ['Link'],
      },
    ],
    'jsx-a11y/anchor-is-valid': [
      'warn',
      {
        components: ['Link'],
      },
    ],
	],
};

나는 이런식으로 설치 후 .eslintrc.cjs 파일에 넣어줬다.

 

4. 린팅 커멘드

ESLint를 사용해 src 디렉토리 내 TypeScript, JavaScript 파일을 검사하는 명령을 추가 등록한다.

 

package.json

{
	"scripts": {
    "lint": "eslint src --ext .tsx,.ts,.jsx,.js",
    "lint:fix": "npm run lint -- --fix"
  },
}

 

이렇게 하면 ESLint 설정은 끝난다! 🎉

근데 ESLint를 설정하면서 느낀게 ESLint를 더 정확히 알아야겠다고 생각이 들었다.

그냥 해야해서 하는게 아니라 왜 하는지 알고 쓰는게 더 바람직할 것 같다.

그래서 다음 글은 Prettier 환경설정을 쓰고 ESLint에 더 깊게 다뤄보도록 할 예정이다. 커밍쑨! 🤓