본문 바로가기

공부/프로젝트

ESLint import, export, object 정렬 자동화 하기 - eslint-plugin-perfectionist 활용

반응형

 

프로젝트에서 코드 스타일을 유지하는 것은 협업과 유지보수에 있어서 매우 중요하다고 생각합니다.

특히 import 순서, 객체 속성 정렬 등은 개발자가 직접 정렬하는 경우가 많아 실수하기 쉽습니다.

이런 반복적인 정렬 작업을 ESlint로 자동화하는 방법에 대해 소개해보려고 합니다.

eslint-plugin-perfectionist 사용 이유 ✨

기존 eslint 플러그인 중에서도 import 정렬을 도와주는 것들이 있습니다.

근데 eslint-plugin-perfectionist는 import, export, 객체, 인터페이스 정렬까지 지원해주고 Custom Grouping과 다양한 정렬 기준을 지원합니다.

그중에서도 제가 제일 필요했던 줄 길이에 따른 정렬을 지원한다는 점에서 eslint-plugin-perfectionist를 사용하게 되었습니다!

 

사용 방법 📖

플러그인 설치

먼저 eslint와 eslint-plugin-perfectionist를 설치합니다.

npm install --save-dev eslint eslint-plugin-perfectionist

 

ESLint 설정 파일 수정

eslint.config.js 또는 .eslintrc.jsperfectionist 플러그인을 추가합니다.

const perfectionist = require('eslint-plugin-perfectionist');

module.exports = [
  {
    ...
    
    plugins: {
      perfectionist
    },
    rules: {
      'perfectionist/sort-imports': [
        'warn',
        {
          type: 'line-length',
          order: 'asc', 
          fallbackSort: { type: 'alphabetical', order: 'asc' },
          groups: [
            'type',
            ['builtin', 'external'],
            'internal',
            ['parent-type', 'sibling-type', 'index-type'],
            ['parent', 'sibling', 'index'],
            'object',
            'unknown'
          ],
          newlinesBetween: 'always',
          customGroups: {
            value: {
              type: ['^type\\s+.*'],
              builtin: ['^node:.*'],
              external: ['^[^./]'],
            }
          },
          internalPattern: ['^@src/(.*)$'],
        }
      ],
      'perfectionist/sort-named-imports': [
        'warn',
        {
          type: 'line-length',
          order: 'asc',
          fallbackSort: { type: 'alphabetical', order: 'asc' }
        },
      ],
      'perfectionist/sort-named-exports': [
        'warn',
        {
          type: 'line-length',
          order: 'asc',
          fallbackSort: { type: 'alphabetical', order: 'asc' }
        },
      ],
      'perfectionist/sort-objects': [
        'warn',
        {
          type: 'line-length',
          order: 'asc',
          fallbackSort: { type: 'alphabetical', order: 'asc' }
        },
      ],
      'perfectionist/sort-interfaces': [
        'warn',
        {
          type: 'line-length',
          order: 'asc',
          fallbackSort: { type: 'alphabetical', order: 'asc' }
        },
      ],
 
    },
  }
];

 

perfectionist/sort-imports

 

sort-imports | ESLint Plugin Perfectionist

Maintain a consistent and sorted order of imports for improved code readability and organization. This ESLint rule helps manage import statements effectively

perfectionist.dev

 

import를 정렬하기 위해 간단하게 설정을 해줍니다.

'perfectionist/sort-imports': [
    'warn',
    {
      type: 'line-length', // ✅ 줄 길이를 기준으로 정렬
      order: 'asc', // ✅ 오름차순 정렬
      fallbackSort: { type: 'alphabetical', order: 'asc' }, // ✅ 동일한 두 요소를 비교할 때 사전순 정렬
      groups: [
        'type', // ✅ TypeScript 타입 import
        ['builtin', 'external'], // ✅ Node.js 내장 모듈과 외부 모듈 (npm 패키지 등)
        'internal', // ✅ 내부 모듈 (프로젝트 내에서 작성한 모듈)
        ['parent-type', 'sibling-type', 'index-type'], // ✅ 부모, 같은 디렉토리, 현재 디렉토리의 인덱스 파일 타입
        ['parent', 'sibling', 'index'], // ✅ 부모, 같은 디렉토리, 현재 디렉토리의 인덱스 파일
        'object', // ✅ 객체 import
        'unknown' // ✅ 정의되지 않은 그룹 (어떤 그룹에도 속하지 않는 import)
      ],
      newlinesBetween: 'always', // ✅ 그룹 간 빈 줄 추가
      customGroups: {
      value: {
          type: ['^type\\s+.*'], // ✅ TypeScript 타입 import를 위한 정규 표현식
          builtin: ['^node:.*'], // ✅ Node.js 내장 모듈을 위한 정규 표현식
          external: ['^[^./]'], // ✅ 외부 모듈 (npm 패키지 등)을 위한 정규 표현식
        }
      },
      internalPattern: ['^@src/(.*)$'], // ✅ @src 경로를 사용하는 내부 모듈을 위한 정규 표현식
    }
],

 

import 정렬 전 후 비교 예시

❌ 정렬 전

import { useEffect } from 'react';
import fs from 'fs';
import axios from 'axios';
import { getData } from '@/utils/api';

 

✅ 정렬 후

import fs from 'fs';

import axios from 'axios';
import { useEffect } from 'react';

import { getData } from '@/utils/api';

 

✅ 동일한 요소 비교 시 사전순 정렬

비교 전 후

 

object, interface 정렬

객체, 인터페이스 정렬

자동 정렬 실행

eslint --fix를 실행하면 자동으로 import 및 object 속성이 정렬됩니다.

npx eslint --fix .

 

vscode에서 ESLint 확장을 사용한다면 settings.json파일에 아래 코드를 추가하고 저장할 때 자동 정렬도 가능합니다.

"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
  "source.fixAll": "explicit",
  "source.fixAll.eslint": "explicit"
},

 

어려웠던 점 ❓

자동 정렬 문제

기존에eslint-plugin-perfectionist 2.11.0 버전을 사용하고 있어서 eslint --fix를 실행할 때 마다 문법 오류가 발생을 했었습니다. 

 

분명 공식 문서에서는 fallbackSort을 사용해서 사전순으로 정렬을 할 수 있었지만 터미널에서는 해당 문법을 사용할 수 없다고 나와 문제를 찾는데 시간이 걸렸는데 eslint-plugin-perfectionist 버전을 최신버전을 업데이트 한 이후에 제대로 동작됐습니다.

 

회고 🧐

eslint-plugin-perfectionist를 활용하면 import, 객체, 인터페이스, export 등 다양한 코드 요소를 자동으로 정렬할 수 있습니다.

 

✔️ 코드 스타일 일관성 유지 

✔️ 수동 정렬하는 번거로움 제거 

✔️ 자동화로 생산성 향상

 

아직 많이 부족하기 때문에 조언은 언제나 환영입니다!


출처 🏷️

https://perfectionist.dev/

반응형