Frontend/전체

ESLint v9 적용하기 (eslint.config.mjs 사용법), eslint 충돌 해결법

전예방 2025. 2. 2. 22:17

 

 

 

React 프로젝트에 ESLint와 Prettier 적용하기

yarn berry 프로젝트 생성하기yarn berry를 사용하는 이유💡 yarn berry를 사용하는 이유에 대해서 알아보자! NPM을 안쓰는 이유?🙋 무겁고 복잡한 node_modules프로젝트의 node_modules 폴더의 용량이 20기가

dpdnjs402.tistory.com

 

전 글에서 ESLint 를 적용하다가 에러가 나서 ESLint 버전을 8로 낮췄다.

이유는 버전 9부터 .eslintrc.json 에서 설정을 셋팅하는게 아니라

eslint.config.mjs 또는 eslint.config.js 등 js 파일에서 설정하는 것으로 바꼈다고 한다.

 

yarn berry boilerplate (ESLint v9 적용한) 는 아래 소스 참고

 

GitHub - yewon97/react_yarn_berry_boilerplate: react, yarn berry boilerplate

react, yarn berry boilerplate. Contribute to yewon97/react_yarn_berry_boilerplate development by creating an account on GitHub.

github.com

 


 

@eslint 공식 사이트 참고

 

공식문서를 살펴보니

Configuration Migration Guide 라는 카테고리가 있어서 적용해봤는데...

안된다... 😭

 

문서를 확인해보면 .eslintrc.json 파일을 읽어서 eslint.config.mjs 파일로 다시 만들어주는 것 같은데

명령어를 실행해서 해봤는데...

뭔가 계속 이런식으로 에러가 뜬다.

라이브러리를 계속 추가로 설치하라고 해서 설치해봤지만... 안됐다.


ESLint 설정 방법

@공식문서를 참고해서 npm을 사용했으면 npm명령어로 yarn을 사용했으면 yarn 명령어를 이용해서

eslint config를 초기 셋팅을 진행할 것이다.

yarn create @eslint/config

 

명령어를 입력하면 셋팅을 위한 질문이 나온다. 자신의 프로젝트 셋팅에 맞춰서 답해주면된다.

1. How would you like to use ESLint?
❯ To check syntax and find problems

2. What type of modules does your project use?
❯ JavaScript modules

3. Which framework does your project use?
❯ React

4. Does your project use TypeScript?
❯ Yes

5. Where does your code run?
❯ Browser

6. eslint, globals, @eslint/js, typescript-eslint, eslint-plugin-react
Would you like to install them now?
❯ Yes

7. Which package manager do you want to use?
❯ yarn

 

설치가 완료되고 나면 eslint.config.mjs 파일이 생성될 것이다.

 

셋팅되고 나서 lint:fix 명령어를 입력해보면

yarn lint:fix 

# package.json
 "scripts": {
    "lint": "eslint src/**/*.{ts,tsx,js,jsx}",
    "lint:fix": "eslint --fix src/**/*.{ts,tsx,js,jsx}"
  }

Warning: React version not specified in eslint-plugin-react settings. See https://github.com/jsx-eslint/eslint-plugin-react#configuration .
이런 경고가 또 뜰 것이다.

eslint-plugin-react가 자동으로 react 버전을 감지 못해서 나는 경고라고 한다.

 

위에 경고 + 내가 .prettierrc에 셋팅해놓은 설정들도 제대로 작동하지 않은 것 같다.


eslint.config.mjs 수정하기

일단 eslint config 완성본은 아래와 같다.

// eslint.config.mjs
import globals from 'globals';
import pluginJs from '@eslint/js';
import tseslint from 'typescript-eslint';
import pluginReact from 'eslint-plugin-react';
import pluginPrettier from 'eslint-plugin-prettier';
import { readFileSync } from 'fs';
import { join } from 'path';

// .prettierrc 파일의 설정을 읽어옵니다.
const prettierConfig = JSON.parse(
  readFileSync(join(process.cwd(), '.prettierrc'), 'utf8'),
);

export default [
  // 1. 파일 매칭, globals, 그리고 React 설정 추가
  {
    files: ['**/*.{js,mjs,cjs,ts,jsx,tsx}'],
    languageOptions: {
      globals: globals.browser,
    },
    settings: {
      // react 플러그인 경고 해결을 위해 React 버전을 자동 감지하도록 설정
      react: {
        version: 'detect',
      },
    },
  },
  // 2. @eslint/js의 기본 추천 규칙
  pluginJs.configs.recommended,
  // 3. typescript-eslint의 추천 규칙
  ...tseslint.configs.recommended,
  // 4. eslint-plugin-react의 flat 추천 규칙
  pluginReact.configs.flat.recommended,
  // 5. Prettier 통합: prettier 플러그인과 .prettierrc의 옵션 (여기서 semi 옵션은 별도로 false로 지정)
  {
    plugins: { prettier: pluginPrettier },
    rules: {
      'prettier/prettier': ['error', { ...prettierConfig }],
    },
  },
];

 

1. react version : 'detect' 설정을 추가해서 eslint-plugin-react가 자동으로 React 버전을 감지하도록 했다.

2. 내가 설정한 .prettierrc 파일을 사용하기 위해

fs와 path 모듈을 사용해 프로젝트 루트의 .prettierrc 파일을 읽어왔고,

prettier 플러그인을 추가한 후, 별도의 config 객체로 추가했다.

3. 기존 .eslintrc.json에서 "extends": ["react-app", "react-app/jest", "plugin:prettier/recommended"] 로 설정했었는데,

flat config 방식에서는 react-app, react-app/jest 관련 내용은 CRA 내부 설정 혹은 eslint-plugin-react의 추천 설정으로 대신 처리했다.

 

위와 같이 수정하니 eslint와 prettier 둘다 잘 작동했다.

 


🚨 오류 발생!!!! 🚨

그냥 ESLint v9 관련해서 참고자료가 많이 나오기 전까지는 그냥 v8을 쓰는게 맞는거같다... 포기...😂

 

ESLint와 Prettier는 잘 작동했지만...

yarn start를 해보니...

이런 에러 뿜뿜... ㅠㅠㅠ

 

왜 발생하나 찾아보니...

ESLint v9 부터 예전 버전에서 사용되던 extensions와 resolvePluginsRelativeTo 옵션이 제거되서 그런다고 한다.

CRA 내부구성과 Flat Config 방식에서 충돌이 나다보니... CRA는 legacy 방식으로 작성되어있어서...ㅎㅎㅎ

이런 기타 등등 여러 요소가 복합적으로 작용해서 위와 같은 오류가 발생했다고 한다.

 

일단 해결한 방법은 craco.config.js 파일을 수정해주니까 됐다.

const CracoAlias = require('craco-alias');

module.exports = {
  plugins: [
    {
      plugin: CracoAlias,
      options: {
        source: 'tsconfig',
        baseUrl: '.',
        tsConfigPath: './tsconfig.paths.json',
      },
    },
  ],
  webpack: {
    configure: (webpackConfig) => {
      // 부모 컴파일러에서 ESLint와 fork-ts-checker 플러그인을 완전히 제거
      webpackConfig.plugins = webpackConfig.plugins.filter((plugin) => {
        const name = plugin.constructor && plugin.constructor.name;
        return (
          name !== 'ESLintWebpackPlugin' &&
          name !== 'ForkTsCheckerWebpackPlugin'
        );
      });

      return webpackConfig;
    },
  },
};

근데 이게 진짜 맞는 방식인지는 모르겠다... 하...

누가 알려줄사람 ㅠ 

 


ESLint v9에 대한 다른 글들

https://www.jadru.com/eslint-920-is-not-ready

https://velog.io/@skiende74/%EC%83%88%EB%A1%9C-%EB%8F%84%EC%9E%85%EB%90%9C-ESLint-flat-config-v9

'Frontend/전체'의 다른글

  • 현재글 ESLint v9 적용하기 (eslint.config.mjs 사용법), eslint 충돌 해결법

관련글