[Lint] ESLint + Prettier 적용하기

zzincode·2025년 1월 17일
0

기타

목록 보기
5/14
post-thumbnail

Lint

코드에서 검사하는 항목

  • 포맷팅 : 일관된 코드 스타일을 유지하도록 하고 개발자로 하여금 쉽게 읽히는 코드를 만들어줌
    ex) 들여쓰기 규칙, 코드 라인의 최대 너비 규칙
  • 코드 품질 : 어플리케이션의 잠재적인 오류나 버그를 예방하기 위함

ESLint : ECAScript 코드에서 문제점을 검사하고 일부는 더 나은 코드로 정정하는 린트도구
Prettier : ESLint의 역할 중 포매팅과 겹치는 부분이 있지만 프리티어는 좀 더 일관적인 스타일로 코드를 다듬음


1. ESLint, Prettier VScode에 확장 프로그램 설치

2. ESLint 설치

  1. ESLint 모듈 설치

    $ npm install -D eslint
    
  2. ESLint 초기화

    $ npx eslint --init

    → 프로젝트 상황에 맞게 질문에 답 선택하여 초기화시키기

⚠️ 그동안의 강의나 블로그 글들을 보면 .eslintrc.json파일이 자동적으로 만들어진다고 나와있을 것이다. 하지만 공식사이트를 확인하면 최신 버전에서 eslint.config.mjs 로 바뀌어 생성되게 된다.

import globals from 'globals';
import pluginJs from '@eslint/js';
import pluginReact from 'eslint-plugin-react';
import eslintPluginPrettier from 'eslint-plugin-prettier';
/** @type {import('eslint').Linter.Config[]} */
export default [
  { files: ['**/*.{js,mjs,cjs,jsx}'] },
  { languageOptions: { globals: globals.browser } },
  pluginJs.configs.recommended,
  pluginReact.configs.flat.recommended,
  rules: {
     //적용하고자 하는 규칙을 넣을 수 있다.
    }
];

ESLint Rules

3. Prettier 설치

  1. Prettier 모듈 설치

    $ npm install -D prettier
  2. 설정파일인 .prettierrc.json 파일 생성

    Prettier options 참고해 원하는 옵션 설정

    // .prettierrc.json
    {
      "singleQuote": true,
      "semi": false,
      "useTabs": false,
      "tabWidth": 2,
      "trailingComma": "all",
      "printWidth": 80,
      "arrowParens": "avoid",
      "bracketSpacing": true,
      "htmlWhitespaceSensitivity": "css",
      "insertPragma": false,
      "jsxBracketSameLine": false,
      "jsxSingleQuote": false,
      "proseWrap": "preserve",
      "quoteProps": "as-needed",
      "requirePragma": false
    }
    

4. ESLint와 Preitter 충돌 없애기

  • eslint-config-prettier 는 프리티어와 충돌하는 ESLint규칙을 끄는 역할을 함
    $ npm install -D eslint-config-prettier
  • eslint-plugin-prettier 는 프리티어 규칙을 ESLint 규칙으로 추가하는 플러그인 → eslint 실행되면 Prettier까지 적용
    $ npm install -D eslint-plugin-prettier
  • eslint.config.mjsplugins, rules 추가
    import globals from "globals";
    import pluginJs from "@eslint/js";
    import pluginReact from "eslint-plugin-react";
    import eslintPluginPrettier from "eslint-plugin-prettier";
    
    /** @type {import('eslint').Linter.Config[]} */
    export default [
      {files: ["**/*.{js,mjs,cjs,jsx}"]},
      {languageOptions: { globals: globals.browser }},
      pluginJs.configs.recommended,
      pluginReact.configs.flat.recommended,
      {
        plugins: {
          prettier : eslintPluginPrettier
        },
        rules: {
          'prettier/prettier': 'error',
        }
      }
    ];
    

5. 저장시 ESLint 자동실행

  1. 기본설정

    Mac : Command + ,

  2. 설정창 - code action on save → setting.json 편집

  3. 해당 코드 수정 및 추가

     "editor.formatOnSave": false, // true-> false로 수정 -> Prettier 충돌 방지
     "editor.codeActionsOnSave": ["source.fixAll.eslint"] // 추가

⚠️ React 에러 발생

eslint.config.mjs에 추가

    rules: {
      'prettier/prettier': 'error',
      'react/prop-types': 'off',
      'react/react-in-jsx-scope': 'off',
    }
     
  • 'react/prop-types': 'off’ : props를 검증하도록 강제하는 린트 규칙을 비활성
  • 'react/react-in-jsx-scope': 'off' : JSX를 사용할 때 React를 반드시 import하도록 요구하는 규칙을 비활성화 *import React from 'react'; 입력되어 있지 않을 때 발생하는 오류

⚠️ Process 오류


Process가 Node에서 사용하는 것이기에 따로 설정을 해줘야함
env는 ESLint 설정에서 코드가 실행되는 환경을 지정하는 옵션 → ESLint가 특정 환경에 맞는 전역 변수(global variables)나 문법을 인식하도록 도와줌

import pluginJs from '@eslint/js';
import pluginReact from 'eslint-plugin-react';
import eslintPluginPrettier from 'eslint-plugin-prettier';

/** @type {import('eslint').Linter.Config[]} */
export default [
  { files: ['**/*.{js,mjs,cjs,jsx}'] },
  { languageOptions: { globals: globals.browser } },
  pluginJs.configs.recommended,
  pluginReact.configs.flat.recommended,
  {
    plugins: {
      prettier: eslintPluginPrettier,
    },
    rules: {
      'prettier/prettier': 'error',
      'react/prop-types': 'off',
      'react/react-in-jsx-scope': 'off',
    },
    env: {
      node: true,
    },
  },
];

0개의 댓글