TIL

eslint replace ... 에러

차가운에스프레소 2023. 5. 23. 17:31

1. 문제상황

- carryduo 프로젝트에서 리팩토링 할 내용이 있어, 간만에 프로젝트를 켰다.

- 리팩토링 할 것은 계층 분리, 테스트 코드와 관련된 것이었는데, 코드의 printWidth가 너무 넓게 설정되어 있는 것이 거슬려서, .prettierrc 파일에서 printWidth를 줄였다.

- 그런데, 다음과 같은 에러가 발생했다.

 error  Replace `↹` with `··`    

↹는 tab, 줄바꿈을 의미한다.
··는 스페이스바, 띄어쓰기를 의미한다.

- 기존의 eslint 설정과 prettier 설정은 다음과 같았다.


1) eslint

module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: 'tsconfig.json',
    tsconfigRootDir: __dirname,
    sourceType: 'module',
    createDefaultProgram: true
  },
  plugins: ['@typescript-eslint/eslint-plugin'],
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  root: true,
  env: {
    node: true,
    jest: true,
  },
  ignorePatterns: ['.eslintrc.js'],
  rules: {
    '@typescript-eslint/interface-name-prefix': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    "prettier/prettier": ["error", { "endOfLine": "auto" }]
  },
};

2) prettier

(1) prettierrc

{
  "singleQuote": true,
  "trailingComma": "all",
  "printWidth": 500
}

(2) IDE setting

- printWidth: 100

- tabWidth: 2

- configPath: .prettierrc

- endOfLine: auto

- singleQuote: true

- trailingComma: none


2. 문제 해결 방법

- 빠르게 해결 방법부터 이야기하자면, 다음 방법을 통해 Replace `↹` with `··` 에러를 해결할 수 있었다.

IDE setting.json에서 eslint 룰에 따른 자동 완성 적용하기

- setting.json에 다음과 같은 파라미터를 추가해줌으로써, eslint의 설정에 따라 자동 완성이 적용되도록 할 수 있다.

- 개인적으로, 이 방법이 가장 확실한 방법이라고 생각한다.

- 만약, editor.formatOnSave가 활성화되어 있다면, 위 기능을 제대로 사용하기 위해서는 비활성화로 변경하는 것이 좋다.

- 왜냐하면, formatOnSave는 eslint와 무관하게 prettier 익스텐션 설정에 기반해서만 자동 완성을 적용하는 파라미터이기 때문이다.

- 실제로, 필자는 formatOnSave를 활성화하고, 아래 source.fixAll.eslint도 활성화한 상태에서 자동완성을 테스트해보았고, source.fixAll.eslint에 의한 자동완성이 다시 formatOnSave에 의해 변경되는 것을 확인할 수 있었다.

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

3. eslint 설정에 대한 간략한 소개 

나는 다음 부분들에서 내가 eslint와 prettier를 아직 잘 모르고 쓰고 있다는 것을 느꼈다.

1. prettierc를 prettier config로 사용하는 것이 IDE에 설정되어 있긴 했지만 IDE 세팅이 prettierrc와 너무 다른 것이 무척 머쓱했다.

2. eslint의 설정들은 사실상 NestJS 프레임워크를 설치할 때 자동으로 세팅되었을 뿐, 어떤 설정이 어떤 의미인지 잘 모르고 있었다.

 

그래서 이번에 위 문제를 해결하면서 살펴본 eslint의 주요한 설정들에 대해서 가볍게 짚고 넘어가고자 한다.(완벽하진 않다. 앞으로 또 코드 스타일 관련해서 eslint에 의한 문제를 겪으면 또 짚으리라...)

 

typescript를 기준으로, 일반적으로 활용되는 eslint 설정은 다음과 같다.

module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: 'tsconfig.json',
    tsconfigRootDir: __dirname,
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint/eslint-plugin'],
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  root: true,
  env: {
    node: true,
    jest: true,
  },
  ignorePatterns: ['.eslintrc.js'],
  rules: {
    '@typescript-eslint/interface-name-prefix': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-explicit-any': 'off'
};

각각의 설정들의 의미는 다음과 같다.

 

- parser: 코드를 검사할 파서이다. 일반적으로 자신이 활용하는 언어/프레임워크에 맞는 플러그인으로 설정한다.

- parseOptions: 말 그대로, 파서가 파싱할 때 부가적으로 적용될 옵션을 의미한다.

- plugins: 코드를 검사할 때 활용할 플러그인을 설정한다.

- extends: plugins에 추가적으로 사용할 rule을 가진 플러그인들을 설정한다.

- ignorePatterns: 린트 적용을 제외할 파일의 패턴을 설정한다.

- env: 환경변수를 활성화시킬 환경을 설정한다.

- root: .eslintrc의 경로를 의미한다.

- rules: plugins, extends에 덧붙일 rule을 설정한다.

 

위에서 prettier와 연동되는 플러그인은 'plugin:prettier/recommended'이다.

이 플러그인은 다음과 같은 설정을 내포하고 있다.

{
  "plugins": ["prettier"],
  "extends": ["prettier"],
  "rules": {
    "prettier/prettier": "error",
    "arrow-body-style": "off",
    "prefer-arrow-callback": "off"
  }
}

- 쉽게 말하면, prettier 플러그인을 등록해, eslint에서 .prettierrc 혹은 IDE의 setting.json(.prettierrc가 없다면)의 규칙을 이용하고, 그 규칙에 맞지 않은 요소는 error로 간주하게 되는 것이다.

- arrow-body-style과 prefer-arrow-callback은 prettier와 eslint를 함께 사용하는 데 발생하는 내부적 이슈를 해소하기 위한 설정이라고 한다.


4. 다시 보는 문제 원인

- typescript에서 일반적으로 사용되는 eslint 설정들에 대해 살펴보고 나서, 다시 문제가 발생된 원인을 되짚어 봤다.

- 필자가 생각하는 Replace `↹` with `··` 가 발생한 원인은 eslint가 코드 자동 완성에 적용되지 않고 있었기 때문이라고 본다.

- 구체적으로, 다음과 같다.

1. formatOnSave는 적용되어 있어, prettier로 코드 자동 완성은 진행된다.

2. 하지만, codeActionsOnSave에 eslint가 비활성화되어 있었기 때문에, prettier로 자동완성은 되었어도, eslint가 자동 완성 기준으로 고려되진 않았다.

3. 그래서 eslint rule들이 적용되지 않아, 코드 상에서 error만 표출된 것이다.

 


5. 결론

- eslint를 사용한다면, 이를 prettier와 연동해서 사용한다면, 다음과 같은 설정들을 해두는 것이 작업에 편리할 것이다.

1. IDE 설정에서 .prettierrc config 경로 적용
2. eslintrc에서 prettier 플러그인 설치
3. .prettierrc에서 프로젝트에서 사용할 코드 스타일 명시
4. codeActionsOnSave 활성화, formatOnSave 비활성화하여 eslint를 코드 자동 완성 시 적용시키기.

- 경험적으로 느낀 것이기 때문에 오류가 있을 수 있습니다. 댓글을 통한 피드백은 언제나 환영입니다!


6. 참고자료

https://helloinyong.tistory.com/325

 

ESLint, Prettier Setting, 헤매지 말고 정확히 알고 설정하자.

ESLint, Prettier 관련해서 환경 세팅을 하면 항상 어쩔 땐 잘되고, 어쩔 땐 안되고... 구글링하면 그렇게 많이 나오는 방식들을 전부 해봐도 계속 안돼서 시간을 그렇게 버릴 때가 많았던 것 같다. 그

helloinyong.tistory.com

https://simsimjae.medium.com/prettier%EC%99%80-eslint%EC%84%A4%EC%A0%95%ED%95%98%EA%B8%B0-%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EC%84%A4%EC%A0%95-110dc8ab94b6

 

prettier와 eslint설정하기(+타입스크립트 설정)

eslint는 보통 잘못 입력한 문법을 자동으로 수정하기 위해서 사용하고 Prettier는 팀원간의 코딩 컨벤션을 맞추기 위해서 사용합니다.

simsimjae.medium.com