[ESLint] import 순서 다루기

이희제·2024년 11월 5일
post-thumbnail

1. sort-imports

eslint에는 기본적으로 sort-imports 가 존재한다. (참고)

각 설정값에 대해서 알아보자.

1. ignoreCase (기본값: false)

  • 대소문자를 무시할지 여부를 설정하는 옵션이다.
  • true로 설정하면 import 문을 정렬할 때 대소문자를 구분하지 않는다.
    • 예: aModuleBModule은 대소문자에 관계없이 정렬된다.
  • false일 경우, 대문자가 소문자보다 먼저 정렬된다.

2. ignoreDeclarationSort (기본값: false)

  • import 선언의 순서를 무시할지 여부를 설정하는 옵션이다.
  • true로 설정하면 import 문 자체의 순서를 검증하지 않는다.
  • 주로 import와 관련된 정렬 오류를 무시하려는 경우 사용된다.

3. ignoreMemberSort (기본값: false)

  • import된 멤버들의 정렬 여부를 무시할지 설정하는 옵션이다.
    • 예: import { b, a } from 'module';에서 멤버 ba의 순서가 검증되지 않는다.
  • true로 설정하면 멤버 간의 알파벳 순서 정렬을 검증하지 않는다.
  • false로 설정하면 멤버들은 알파벳 순으로 정렬되어야 한다.
    • 올바른 예: import { a, b } from 'module';

4. memberSyntaxSortOrder (기본값: ["none", "all", "multiple", "single"])

  • 서로 다른 유형의 import를 정렬하는 순서를 정의하는 옵션이다.
  • 배열 안의 4가지 요소는 항상 포함되어야 하며, 순서를 변경할 수 있다:
    1. none: 바인딩 없이 모듈 자체만 import하는 방식이다.
      • 예: import 'module';
    2. all: 모든 멤버를 한 번에 가져오는 방식이다.
      • 예: import * as utils from 'module';
    3. multiple: 여러 멤버를 가져오는 방식이다.
      • 예: import { a, b } from 'module';
    4. single: 하나의 멤버만 가져오는 방식이다.
      • 예: import a from 'module';

5. allowSeparatedGroups (기본값: false)

  • import 그룹을 별도로 분리할지 여부를 설정하는 옵션이다.
  • true로 설정하면 서로 다른 import 그룹 사이에 빈 줄을 넣는 것을 허용한다.
    • 예:
      javascript
      코드 복사
      import React from 'react';
      
      import { a } from 'module-a';
      import { b } from 'module-b';
      
  • false로 설정하면 그룹 간의 빈 줄을 허용하지 않는다.

2. eslint-plugin-import

eslint-plugin-import 플러그인의 import/order 규칙을 사용해서 ESLint에서 import 구문을 정렬할 수 있다. 코드 가독성을 높이고 일관된 import 구조를 유지하기 위해 사용된다. (참고)

더 상세히 import 순서를 변경할 필요가 있었기 때문에 해당 플러그인을 적용했었다.

eslint-plugin-import의 import/order 적용 방법

  1. 설치
pnpm add -D eslint-plugin-import
  1. ESLint 설정 파일(.eslintrc 또는 .eslintrc.json)에 규칙 추가
  • ESLint 규칙은 합의 후 결정하면 될 것 같습니다.

{
  "plugins": ["import"],
  "rules": {
    "import/order": [
      "error",
      {
        "groups": [
          "builtin", // Node.js 기본 모듈
          "external", // 외부 라이브러리
          "parent", // 부모 파일
          "sibling", // 형제 파일
          "internal", // 내부 모듈
          "type" // 타입 파일
        ],
        "pathGroups": [
          { "pattern": "@/**", "group": "parent" } // path 별칭이 있으면 parent 그룹으로 넣어줬다.
        ],
        "pathGroupsExcludedImportTypes": ["type"], // type 그룹은 pathGroups 룰 제외하기 위해 넣었다.
        "alphabetize": {
          "order": "asc", // 알파벳 순서로 정렬
          "caseInsensitive": true // 대소문자 구분 없음
        },
        "newlines-between": "always" // 그룹 사이에 빈 줄 추가
      }
    ],
  }
}

그룹 옵션(참고)

  1. builtin: Node.js 기본 내장 모듈 (예: fs, path).
  2. external: node_modules에서 가져오는 외부 모듈 (예: react, lodash, axios).
  3. internal: 프로젝트 내부에서 가져오는 모듈 (예: @/utils, src/config).
  4. parent: 상위 디렉토리에서 가져오는 모듈 (예: ../utils).
  5. sibling: 동일한 디렉토리에서 가져오는 모듈 (예: ./Button).
  6. index: 현재 디렉토리의 index 파일을 가져오는 경우 (예: ./).
  7. type : TypeScript의 타입 전용 import (예: import type { MyType } from "./types").
  8. object : 구조분해 할당된 객체 import (ES2020에서 추가된 import * as something from "module" 형태).
  9. unknown : 그룹에 속하지 않는 import (알 수 없는 경로나 형식)
속성(property)필수(required)유형(type)설명(description)
pattern☑️string매칭할 import 구문을 위한 Minimatch 패턴 (필수).
patternOptionsobjectMinimatch 옵션; 기본값: { nocomment: true }.
group☑️사전 정의된 그룹 값매칭된 import가 상대적으로 위치할 사전 정의된 그룹 중 하나 (필수).
position"after""before"

자동 정렬 실행

ESLint를 사용해서 import 정렬을 실행할 수 있다. (자동 저장 혹은 cli를 통해 코드를 자동으로 변경)

eslint --fix .
profile
그냥 하자

0개의 댓글