Front-End/Next.JS

[NextJS / Typescript] Eslint + Prettier 설정 후 husky로 자동화하는 법

koh1018 2022. 7. 27. 23:37
반응형
npx eslint --init

터미널을 키고 위 명령어를 입력하여 .eslintrc.js 파일 만들기

 

위와 같이 질문에 체크하면 된다.

중간에 Which style guide do you want to follow?에는 에어비엔비 스타일로 해도되고 취향것 하면 된다.

 

그럼 추가로 dependencies가 필요하다고 하는데 설치하면된다. 필자는 npm으로 설치했다.

 

.eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2021: true
  },
  extends: [
    'plugin:react/recommended',
    'standard'
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true
    },
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  plugins: [
    'react',
    '@typescript-eslint'
  ],
  rules: {
  }
}

그럼 위와 같이 파일이 생성된다. 여기서 rules 안에

rules: {
    'react/react-in-jsx-scope': 'off'
  },

을 추가하고(React 17부터 react import를 안해도 되는데 eslint가 딴지를 걸어서 off하는 것이다) rules 밑에

settings: {
    react: {
      version: 'latest'
    }
  }

를 적는다.

 

(이해가 안되면 아래 사진 참조)

 

됐으면 root 폴더에 .eslintignore 파일을 만든다.

.next
next-env.d.ts
node_modules
yarn.lock
package-lock.json
public

그리고 위 내용을 작성한다.

 

 

이제 prettier를 설치하겠다.

npm i -D prettier
npm i -D eslint-config-prettier

 

그리고 아까 위에서 만든 .eslintrc.js 의 extends에 'prettier'를 추가한다.

 

이제 prettier 설정 파일인 .prettierrc를 만든다.

 

.prettierrc

{
  "printWidth": 100,
  "tabWidth": 2,
  "trailingComma": "all",
  "singleQuote": true,
  "jsxSingleQuote": true,
  "semi": false
}

설정은 공식문서보면서 어떤 설정이 뭔지 보고 원하는거 취향껏 설정하면 된다.

(webstorm에서는 .prettierrc파일 변경 후 파일 마우스 오른쪽 클릭해서 'Prettier 코드 스타일 규칙 적용'을 눌러줘야 적용 된다.)

 

 

다 했으면 .prettierignore 파일도 만들어준다.

.next
next-env.d.ts
node_modules
yarn.lock
package-lock.json
public

그리고 위 내용 또 작성해준다.

 

 

 

이제 위 eslint와 prettier를 자동화해줄 수 있는 husky를 설치해보겠다.

husky는 git hook으로 commit 할 때 eslint와 prettier를 자동으로 실행하게 해줄 수 있다.

npm i -D husky

 

그런데 매번 커밋할 때마다 파일 전체를 다 eslint와 prettier로 검사하면 시간이 오래 걸릴 것이다.

그래서 조금 더 최적화 할 수 있는 방법이 lint-staged이다.

이걸 사용하면 커밋하려는 내용(변경된 내용)에 대해서만 작업을 수행한다.

npm i -D lint-staged

 

모두 설치했으면, package.json 파일에 다음을 추가한다.

"husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{ts,tsx}": [
      "prettier --write",
      "eslint --fix"
    ]
  }

 

그리고 스크립트 명령어의 경우 다음과 같이 할 수도 있다.

"scripts": {
    "lint": "prettier pages components --write && eslint pages components --fix"
  },

이렇게 해두고 npm run lint 하면 pages폴더와 components 폴더의 모든 파일들이 리팩토링된다.

반응형