eslint 설정하기

1 minute read

Eslint 설정하기

이번 글에서는 eslint 설정에 대해 알아보겠습니다 :P

eslint

우선 eslint를 설치해줍니다

$ npm install -D eslint

eslint 초기화를 위해 하기와 같이 --init 옵션을 붙여 eslint를 실행해 줍니다.

$ ./node_modules/.bin/eslint --init

원하는 eslint 스타일을 선택해 줍시다. 저는 airbnb-base 스타일을 설정 하였습니다 :)

? How would you like to configure ESLint? Use a popular style guide
? Which style guide do you want to follow? Airbnb (https://github.com/airbnb/javascript)
? Do you use React? No
? What format do you want your config file to be in? YAML
Checking peerDependencies of eslint-config-airbnb-base@latest
The config that you've selected requires the following dependencies:

eslint-config-airbnb-base@latest eslint@^4.19.1 || ^5.3.0 eslint-plugin-import@^2.14.0
? Would you like to install them now with npm? (Y/n) Y

설정이 완료되었다면 하기와 같이 .eslintrc 파일이 설정 되셨을 겁니다.

extends: airbnb-base

앞으로 lint를 쉽게 실행하기 위해 package.json에 run-script로 추가해 줍시다.

{
  ...
   "scripts": {
    ...
    "lint": "./node_modules/.bin/eslint src"
  },
  ...
}

설정을 하였으니 lint가 제대로 동작하는지 확인해 봅니다.

$ npm run lint

> setup-es8@1.0.0 lint /Users/juno/Documents/nodejs/node-boilerplate
> eslint src

/Users/juno/Documents/nodejs/node-boilerplate/src/__test__/calc.test.js
  3:1  error  'describe' is not defined                      no-undef
  4:3  error  'it' is not defined                            no-undef
  5:5  error  'expect' is not defined                        no-undef
  7:4  error  Newline required at end of file but not found  eol-last

/Users/juno/Documents/nodejs/node-boilerplate/src/calc.js
  1:1   error  Prefer default export                          import/prefer-default-export
  1:38  error  Newline required at end of file but not found  eol-last

✖ 6 problems (6 errors, 0 warnings)
  2 errors and 0 warnings potentially fixable with the `--fix` option.

에러가 많이 나옵니다. 이제 하나씩 아래와 같이 고쳐보겠습니다.

const sum = (a, b) => (a + b);
export default sum; // export가 하나 일 경우에는 export default를 권장합니다.
 // 파일 끝은 항상 new line이 들어가는 것을 권장합니다.

test.js파일에서 발생하는 에러는 eslint-plugin-jest를 설치하여 해결합니다.

$ npm install -D eslint-plugin-jest

설치 후 아래 처럼 .eslintrc 파일을 고쳐주겠습니다.

extends: airbnb-base

plugins: 
  - jest

env:
  "jest/globals": true

lint를 통과하였습니다.

$ npm run lint

> setup-es8@1.0.0 lint /Users/juno/Documents/nodejs/node-boilerplate
> eslint src

지금까지 nodejs 프로젝트를 위해 많이들 사용하시는 babel, jest, eslint 설정에 대해 알아보았습니다.