node.js에 eslint 와 typescript 적용하기

Yeonjoo Yoo·2022년 1월 25일
0

TIL

목록 보기
2/12
사이드 프로젝트에 backend를 node.js로 개발하면서, 코드를 더 안전하고 가독성 좋게 작성할 수 있도록 eslint와 typescript를 적용하기로 했다.
적용했던 과정을 정리하고자 한다.

참고로, 사이드 프로젝트에서 node.js의 모듈 시스템은 ES6을 사용
(Node.js의 기본 모듈 시스템은 commonJS)

eslint

eslint 란?

  • js 코드에서 에러가 날 만한 부분을 코드 레벨에서 줄여줄 수 있도록 도와주는 문법 보조 도구
  • prettier와 함께 사용하여 사용자의 coding convention을 넣어서 작성 가능
  • .eslintrc : eslint 설정 파일 (js, yml, json)

eslint 적용 과정

라이브러리 설치

npm install @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint eslint-config-prettier eslint-plugin-prettier prettier -D

.eslintrc.json 설정 파일 추가

  • env 옵션
    • 이미 정의된 전역 변수 사용을 정의
    • 자주 사용되는 설정 : browser, node
    • 예를 들어, browser, node 설정을 하지 않을 경우 console, require 같은 사전 정의된 전역변수 환경에 있는 static 메서드를 인식할 수 없어서 에러가 발생
    • globals 옵션을 이용하여 사용자 정의 전역 변수 추가 가능
{
  "root": true,
  "env": {
    "node": true,
    "browser": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:@typescript-eslint/eslint-recommended"
  ],
  "plugins": ["prettier", "@typescript-eslint"],
  "parserOptions": {
    "parser": "@typescript-eslint/parser",
    "sourceType": "module"
  },
  "rules": {
    "no-console": "off",
    "no-debugger": "warn",
    "prettier/prettier": [
      "error",
      {
        "singleQuote": true,
        "semi": true,
        "useTaps": true,
        "tabWidth": 2,
        "trailingComma": "all",
        "printWidth": 80,
        "bracketSpacing": true,
        "arrowParens": "avoid"
      }
    ]
  }
}

적용 중 이슈

  • .eslintrc.js 의 확장자를 cjs로 변경하라는 오류
    • ES6 module system을 사용해서 발생 (package.json에 "type": "module" 추가)
    • .eslintrc.json으로 변경하여 처리
  • import : Parsing error: 'import' and 'export' may appear only with 'sourceType: module'
    • .eslintrc.json > parserOptions에 "sourceType": "module" 옵션 추가
  • Parsing error: sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding { ecmaVersion: 2015 } to the parser options
    • .eslintrc.json > env 에 "es2021": true 옵션 추가 또는
      .eslintrc.json > parserOptions 에 "ecmaVersion": "latest" 옵션 추가
  • Parsing error: Unexpected token
    • ts 파일에 type annotation 사용 시 에러 발생
    • .eslintrc.json > parserOptions에 "parser": "@babel/eslint-parser" 옵션 추가
    • .eslintrc.json > parserOptions에 "parser": "@typescript-eslint/parser" 옵션 추가
      • ESLint의 parser는 기본적으로 ECMAScript 5 syntax를 지원하게되어 있지만, 옵션으로 특정 버전을 지정할 수 있음
      • "@babel/eslint-parser"를 install하고 설정에 추가했지만, TS 적용 시 동일한 에러 발생. babel-parser가 ts 문법을 잘 해석하지 못하는 것으로 추측됨.
      • 따라서, "@typescript-eslint/parser"로 변경

typescript

typescript 란?

  • 자바스크립트에 타입을 부여한 언어 (슈퍼셋)
  • 에러를 사전에 방지할 수 있고, vscode 사용 시 코드 가이드 및 자동 완성 기능으로 개발 생산성 향상 가능

typescript 적용 과정

라이브러리 설치

npm install typescript -D

tsconfig.json 설정 파일 추가

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": true,
    "target": "es5",
    "outDir": "./dist",
    "moduleResolution": "Node",
    "lib": ["ES2015", "DOM", "DOM.Iterable"],
    "noImplicitAny": true,
    "typeRoots": ["./node_modules/@types", "types"],
    "strict": true,
    "useUnknownInCatchVariables": false,
    "esModuleInterop": true
  },
}

참고
https://velog.io/@kyusung/eslint-config-2
https://velog.io/@josworks27/ESLint-Prettier-%EC%84%A4%EC%A0%95-%EB%B0%B1%EC%97%94%EB%93%9C
https://stackoverflow.com/questions/36001552/eslint-parsing-error-unexpected-token
https://r4bb1t.tistory.com/68
https://eslint.org/docs/user-guide/configuring/language-options

profile
to be frontend engineer

0개의 댓글