우당탕탕 개발일기

[Eslint] import 자동 정렬은 Eslint로! 본문

What I Learned/etc.

[Eslint] import 자동 정렬은 Eslint로!

rilee 2023. 2. 16. 09:53
728x90

여러명이 협업하는 경우... 다 제각각 코드 작성 스타일이 다르다.

이걸 맞춰나가는게 협업이라지만, 이런것까지 맞춰야하나 싶은 생각이 들기도 한다.

그 '이런것'에 해당하는 것 중 하나가 import 정렬이었는데....

Eslint에서 import order를 설정할 수 있다고 한다!!

 

즉, eslint에게 규칙만 알려주면 많은 사람들이 제각각 import 해와도 자동으로 정해진 규칙대로 정렬이 되는 것!!!

 

일단, eslint부터 설치해준다!

npm install -D eslint

이때 확장에서 eslint도 함께 설치해주어야 한다.

 

그리고 프로젝트의 root 위치에서 .eslintrc.js이라는 파일을 만들어주어 그 안에서 이제 규칙을 작성하면 된다.

 

기본 순서는 ["builtin", "external", "parent", "sibling", "index"] 이다.

builtin : 내장 모듈

external: 외부 라이브러리 (ex. react, ...)

internal: 내부 파일들

parent: 상위 폴더의 파일들

sibling: 동일한 폴더 내 파일들

index: index 파일들

 

나는 리액트와 같은 라이브러리 > 내부 모듈 > 기타 파일(scss 등) 순으로 정렬되기를 바라서 

아래와 같이 작성해주었다.

module.exports = {
 // ...,
 
  rules: {
    "import/order": [
      "error", // 작성 규칙에 맞지 않으면 경고를 띄운다는 뜻
      {
        "newlines-between": "always", // 각 구분마다 엔터를 넣는다는 뜻
        groups: [ // import 순서
          "external",
          "builtin",
          "parent",
          "sibling",
          "internal",
          "index",
          "type"
        ],
        pathGroups: [ //일종의 커스텀 적용
          {
            pattern: "react*",
            group: "external",
            position: "before"
          },
          {
            pattern: "폴더명/*",
            group: "internal",
            position: "before"
          }
        ],
        pathGroupsExcludedImportTypes: ["react"],
        alphabetize: { // 알파벳 순서
          order: "asc",
          caseInsensitive: true
        }
      }
    ]
  },
  settings: {
    "import/parsers": {
      "@typescript-eslint/parser": [".ts", ".tsx"]
    },
    "import/resolver": {
      node: {
        paths: ["src"] // 절대경로를 이용할 때
      }
    }
  }
  //...
};

 

 

 "external", "builtin","parent", "sibling", "internal",  "index", "type" 순으로 하되

리액트~로 시작하는 라이브러리들을 external 중에서도 앞에,

특정 폴더에 있는 파일들은 internal 중에서도 앞에로 두게 하였다.

 

pathGroups를 적었는데도 만약 적용이 안된다면,

밑의 pathGroups~ 도 작성해주어야 적용이 된다고 하니 참고!

 

 

https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/order.md

 

GitHub - import-js/eslint-plugin-import: ESLint plugin with rules that help validate proper imports.

ESLint plugin with rules that help validate proper imports. - GitHub - import-js/eslint-plugin-import: ESLint plugin with rules that help validate proper imports.

github.com

 

https://www.daleseo.com/eslint-config/

 

 

(+) 이랬는데, ESLint 자동수정이 안된다는 의견이 접수됐다!

반드시 setting.json(Ctrl + p로 검색)에  "editor.codeActionsOnSave": { "source.fixAll.eslint": true },을 추가해주어야 자동 수정이 작동한다! 아니면 그냥 빨간 밑줄만 나오고 수동으로 수정해야함..!


https://tesseractjh.tistory.com/306#--%--eslint-codeActionsOnSave-rules

728x90