client/web

[기록] lint - ESLint, prettier, husky, ...

growww 2022. 3. 16. 21:41

inflearn - 프론트엔드 개발환경의 이해와 실습 (webpack, babel, eslint..) - 김정환 님

강의를 들으며 기록한 내용이다.

 

 

기본 이론

  • 린트의 역할 코드의 보푸라기들을 제거하는 역할을 한다
<script>
    console.log()
    (function(){})
    // Uncaught TypeError: console.log(...) is not a function

    // 아래 처럼 실행되는게 아니라 타입 오류가 난다
    // console.log();
    // (function(){});

    // 아래 처럼 인식한다
    // console.log()(function(){})()
</script>

 

  • ESLint 역할
  1. 포맷팅
  2. 코드 품질 유지 : 잠재적 오류를 사전에 체크해 줌

 

실습 준비 및 실습

  • ESLint 사용
    • npm i eslint 실행
    • npx eslint app.js 실행하면 오류남
// 설정 파일이 필요하다
ESLint couldn't find a configuration file. To set up a configuration file for this project, please run:
    npm init @eslint/config

프로젝트 루트에 .eslintrc.js 파일을 생성

// 내용을 일단 껍데기만 작성
module.exports = {
    
}

 

  • npx eslint app.js 실행하면 오류 없이 실행은 되나 아무 반응이 없음
  • ESLint 에는 규칙이 있다
// .eslintrc.js 파일 내용 수정
module.exports = {
    rules: {
        "no-unexpected-multiline" : "error" // 함수와 괄호 사이에 기대하지 않은 줄바꿈이 있으면 오류남
    }
}

// npx eslint app.js 실행 결과 
/Users/choise/Downloads/my_gitlab/_mine/basic_lint/app.js
  2:1  error  Unexpected newline between function and ( of function call  no-unexpected-multiline

// app.js 내용 수정
console.log();
(function(){})();

 

  • npx eslint app.js 실행하면 다시 오류 없이 실행됨
// 세미콜론 여러개 쓸 경우 에러를 주는 규칙
module.exports = {
    rules: {
        "no-unexpected-multiline" : "error",
        "no-extra-semi" : "error"
    }
}

// app.js 내용 수정
console.log();;;
(function(){})();

// npx eslint app.js 실행 결과 
/Users/choise/Downloads/my_gitlab/_mine/basic_lint/app.js
  1:15  error  Unnecessary semicolon  no-extra-semi
  1:16  error  Unnecessary semicolon  no-extra-semi
  1:17  error  Unnecessary semicolon  no-extra-semi
✖ 3 problems (3 errors, 0 warnings)

// npx eslint app.js --fix 하면 코드 자동으로 수정 해줌 
// 실행 결과 app.js 수정됨  
console.log();
(function(){})();

 

  • ESLint 규칙 세트 규칙을 하나씩 적용하는게 아니라 세트로 적용 가능하다
// .eslintrc.js 파일 내용 수정
module.exports = {
    extends : [
        "eslint:recommended"
    ]
    // rules: {
    //     "no-unexpected-multiline" : "error",
    //     "no-extra-semi" : "error"
    // }
}
  • app.js 에 세미콜론 적용, 세미콜론 삭제를 하면 위에서 발생했던 오류들이 다시 발생하여, eslint 규칙들이 잘 적용된 것을 확인할 수 있음
  • eslint 규칙 세트에는 recommended 외에 airbnb, standard 설정 등 도 제공해 줌

 

  • ESLint 설정
    • .eslintrc.js 파일을 보통 자동으로 생성하여 사용한다
// npx eslint --init 실행하고 아래 옵션들을 선택한다
You can also run this command directly using 'npm init @eslint/config'.
Need to install the following packages:
  @eslint/create-config
Ok to proceed? (y) y
✔ How would you like to use ESLint? · problems
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · none
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser
✔ What format do you want your config file to be in? · JavaScript
Local ESLint installation not found.
The config that you've selected requires the following dependencies:

eslint@latest
✔ Would you like to install them now with npm? · No / Yes
Installing eslint@latest


// 자동완성된 .eslintrc.js 파일
module.exports = {
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "rules": {
    }
}

 

  • ESLint 실습
    • npm i eslint 로 설치
    • npx eslint --init 으로 .eslintrc.js 기본파일 생성 및 "extends": "eslint:recommended" 추가여부 확인
// 실행 방법 1
npm run build 후 app.js 내 ;;; 중복 세미콜론 삭제 여부 확인 

// 실행 방법 2

// package.json 파일에 아래 lint 추가 
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "lint": "eslint src --fix" // src 하위 파일들 검사하고 자동 수정되는 코드들은 수정하게끔 설정 
},

// app.js 파일에 내용 수정
const foo = '';
console.log();
(function(){})();

// npm run lint 실행
  > basic_lint@1.0.0 lint
  > eslint src --fix
  /Users/choise/Downloads/my_gitlab/_mine/basic_lint/src/app.js
    2:7  error  'foo' is assigned a value but never used 

// app.js 파일에서 아래 내용 삭제 하면 다시 잘 돌아감
const foo = '';

 

프리티어

  • 프리티어
    • ESLint의 포매팅 기능을 강화한 도구
    • npm i prettier 로 설치
    • npx prettier src/app.js --write 로 자동 수정 시행
  • 프리티어와 eslint 를 동시에 쓰자
    • npm i eslint-config-prettier 로 설치
// 아래 두번 실행 eslint 적용, prettier 적용
npx eslint src/app.js --fix 
npx prettier src/app.js --write

// 두번 실행 귀찮다 한번에 하자
// npm i eslint-config-prettier eslint-plugin-prettier 실행 : eslint 안에 prettier를 넣어버린 플러그인
// .eslintrc.js 파일에 아래 설정 하면됨
// 주석의 extends, plugins, rules 로 설정하지 말고 extends로 한번에 설정 가능
module.exports = {
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": ["eslint:recommended", "plugin:prettier/recommended"],
    // "extends": ["eslint:recommended", "eslint-config-prettier"],
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    // plugins: [
    //     "prettier"
    // ],
    // "rules": {
    //     "prettier/prettier" : "error"
    // }
}
//  npx eslint src/app.js --fix 로 한번 실행하면 eslint + prettier 동시 적용됨

 

  • 린트와 프리티어 자동화 깃을 사용하면 깃을 푸쉬/커밋할 때 깃훅으로 린트와 프리티어 적용
    • 이때 허스키(husky)를 사용
    • npm i husky 실행
// package.json 내용 수정
{
  "name": "basic_lint",
  ... ,
  "husky": {
    "hooks": {
      "pre-commit": "echo \"이것은 커밋전에 출력됨\""
    }
  }
}

// "pre-commit": "eslint src/app.js -- fix" 로 수정하여 자동으로 실행 되게 함

 

  • 깃 커밋할때 변경된 파일에만 린트와 프리티어 적용하기
    • npm i -D lint-staged
// package.json 내용 수정
{
  ... ,
  "husky": {
    "hooks": {
      "pre-commit": "eslint src/app.js -- fix"
    }
  },
  "lint-staged": {
    "*.js": "eslint --fix"
  }
}

 

  • VSCode 에디터에서도 사용할 수 있다
  1. extension 으로 eslint 설치
  2. Settings > Workspace Settings > settings.json 내용 수정

 

// settings.json 내용
{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "editor.formatOnSave": true
}

 

 

https://www.inflearn.com/course/%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%94%EB%93%9C-%EA%B0%9C%EB%B0%9C%ED%99%98%EA%B2%BD/dashboard