연습장

eslint 공부 본문

기타

eslint 공부

js0616 2024. 8. 13. 20:11

https://www.youtube.com/watch?v=Y3kjHM7d3Zo&t=97s

 

장점

코드 포매팅 : 일관된 코딩 컨벤션을 유지하는 기능

코드 품질 : 잠재적인 오류를 찾아주는 기능

 

eslint 설치  // 해당 영상 기준 버전

npm install --save-dev eslint@6.8.0

 

옛날 버전이라고 경고하는 모습

 

.eslintrc.js 파일 생성

빈 객체를 만들어서 노드 형식의 모듈을 생성

-> v9.0.0 부터는 eslint.config.js 로 생성

module.exports = {
   
}

 

npm 스크립트에 'lint' 명령어 등록

  "scripts": {
    "lint": "eslint src"
  },

 

 

[폴더 구조]

 

app.js 생성

// ./src/app.js
console.log()
(function(){})()

 

npm run lint 로 실행 


규칙 (Rules) 추가

// eslint.config.js
module.exports = {
    rules : {
        "no-unexpected-multiline":"error"
    }
}  

 

npm run lint 실행

 

추가한 rule 의 에러가 발생하는것을 확인.

 

세미콜론을 넣어서 app.js 파일을 수정

// ./src/app.js
console.log();
(function(){})();

 

다시 npm run lint 수행

 

이상 없이 검사를 통과하게 됨 

 

그 외 규칙들

 

https://eslint.org/docs/latest/rules/

 

Rules Reference - ESLint - Pluggable JavaScript Linter

A pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.

eslint.org


'--fix' 옵션

 

// eslint.config.js
module.exports = {
    rules : {
        "no-unexpected-multiline":"error",
        "no-extra-semi":"error"
    }
}  

 

추가적인 세미콜론을 허락하지 않는 rule

// ./src/app.js
console.log();;;;;;;
(function(){})();

 

npm run lint 

 

--fix 옵션 추가

{
  "name": "eslint",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "lint": "eslint src --fix"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "eslint": "^9.9.0"
  }
}

 

 

자동으로 app.js 의 코드를 수정해주는것을 확인

 

모든 룰이 다 자동 수정 되는것이 아니고, 

아래와 같이 랜치가 활성화 된 룰만 --fix 로 자동으로 수정이 가능

 

 

초록색 체크박스는 eslint 가 권장하는 rule 로 이를 모아놓는게 recommended 이다.

기존 rule 은 recommended 에 포함되므로 제거, 포함되지 않는건 따로 추가 하면된다.


eslint recommended 사용하기

 

// eslint.config.js
module.exports = {
    extends : [
        "eslint:recommended"
    ]
}  

 

app.js 를 오타를 내고 

// ./src/app.js
console.log();;;;;;;;;
(function(){})();

 

npm run lint 실행

 

console 을 인식하지 못함

 

ESLint의 기본 설정은 Node.js 환경을 기준으로 하며, console을 정의하지 않는 경우가 있습니다.

 

.eslintcr.js 파일 수정

// .eslintrc.js
module.exports = {
    env: {
        browser: true,  // 브라우저 전역 변수를 인식합니다.
        node: true      // Node.js 전역 변수를 인식합니다.
    },
    extends : [
        "eslint:recommended"
    ]
}  

 


Prettier 설치

npm install --save-dev prettier

Prettier 는 eslint 와 달리 규칙이 미리 설정되어 있어 바로 사용 가능 

 

npx prettier src/**/*

파일 읽기?

 

npx prettier src/**/* --write   

prettier 양식으로 write

 

// ./src/app.js
foo(realrealreal(), eslint_so_hard(), thereAreManySetting(), isDrivingMeCarzy());

 

npx prettier src/**/* --write   

자동으로 줄바꿈 되고 , 도 추가 됨 

// ./src/app.js
foo(
  realrealreal(),
  eslint_so_hard(),
  thereAreManySetting(),
  isDrivingMeCarzy(),
);

 

프리티어는 코드문맥을 파악하고 상황에 따라 최적의 모습으로 코드를 만들어 준다. 

-> 코드의 '일관성' 을 유지할 수 있음


합쳐서 사용하기

eslint : 코드 품질 관련 검사  +  prettier : 포매팅

 

eslint-config-prettier & eslint-plugin-prettier 

프리티어 포매팅 규칙을 eslint 로 추가하고 서로 충돌하는 옵션이 있으면 프리티어의 규칙을 사용하도록 한다. 

npm install --save-dev eslint-config-prettier@6.10.0 eslint-plugin-prettier@3.1.2

 

// .eslintrc.js
module.exports = {
    env: {
        browser: true,  // 브라우저 전역 변수를 인식합니다.
        node: true      // Node.js 전역 변수를 인식합니다.
    },
    extends : [
        "eslint:recommended",
        "plugin:prettier/recommended"
    ]
}  

 

eslint 만 실행해도 둘다 실행한 효과가 난다. 

 

아니 왜 또 안된다.. 뭐가 문젠데.. 다해줬잖아...  영상과 다른건 프리티어 버전밖에 없는거같은데 ... 

 

커밋시 검사하는 기능 

익스텐션 설치 + 저장할때마다 검사 하는 기능

 

에 대한 부분이 남았는데, 나머지 영상 참고.. 

 

 

eslint 도 결국 npm 으로 실행해서 검사하는 기능이다. 

prettier 를 포함시켜서 사용할 수 있다. 

익스텐션을 설치하고 저장 시에 검사하도록 하면 vscode 에서 바로 바로 확인 가능하다. 

CRA (create-react-app) 사용시 eslint 가 포함되어있다. 

 

 

 

내가 해보고 싶은것 

1. eslint 9 이상 버전의 recommended 로 세팅하기

2. eslint airbnb 룰로 세팅하기 (완)

 

 

9 이상의 버전에선 

 

eslint.config.js 파일을 생성해서 적용해야 된다는데 , 다음에 시간될때 해보도록 함.. 

https://eslint.org/docs/latest/use/configure/configuration-files#using-predefined-configurations

 

Configuration Files - ESLint - Pluggable JavaScript Linter

A pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.

eslint.org

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'기타' 카테고리의 다른 글

갑자기 구글 검색시 한글 진하게(볼드체) 적용됨  (0) 2024.08.22
eslint 공부 - airbnb  (0) 2024.08.13
쿠키, 세션  (0) 2024.07.30
MobX 란  (0) 2024.07.30
redux  (0) 2024.07.30