ESLint

Eye0n·2020년 12월 6일
0

ESLint

목록 보기
1/1

이 문서는 ESLint 공식문서를 참고하여 작성되었습니다.

ESLint

ESLint is an open source JavaScript linting utility

Code linting은 빈번하게 문제가 있는 패턴들 또는 스타일 가이드라인을 따르지 않는 코드를 찾기 위해 사용되는 정적 분석 타입입니다.

ESLint는 개발자에게 JavaScript code를 실행하지 않고 문제를 찾게 해줍니다.

ESLint Configuring은 .eslintrc.{js,yml,json}파일 또는 package.json파일 eslintConfig필드에 작성합니다.

  • 특징
    • Find Problems
    • Fix Automatically
    • customize

1. Installation and Usage

install

  • npm install eslint --save-dev
  • yarn add eslint --dev

initialize

  • npx eslint --init
  • yarn run eslint --init

📌 eslint을 직접 설정해줘도 되지만 이미 만들어져서 사용되는 style guide 가 있다. 아래 사진을 보면 style guide로 airbnb(eslint-config-airbnb) 를 선택했습니다.

생성된 airbnb style의 .eslintrc.json

excute

  • npx eslint yourfile.js
    or
    yarn run eslint yourfile.js

2. Configuration

ESLint를 구성하는 두 가지 기본 방법이 있습니다.

    1. Configuration Comments - use JavaScript comments to embed configuration information directly into a file.

    1. Configuration Files - use a JavaScript, JSON or YAML file to specify configuration information for an entire directory and all of its subdirectories.

There are several pieces of information that can be configured:

  • Environments : 스크립트가 실행되도록 설계된 환경, 각 환경에는 미리 정의 된 특정 전역 변수 세트가 함께 제공됩니다.

  • Globals : 스크립트가 실행 중에 접근하는 추가 전역 변수.

  • Rules : 활성화 된 규칙 및 오류 수준.

2.1 Parser Options

기본적으로 ESLint는 ECMAScript 5을 예상합니다. parserOptions을 사용하여 JSX뿐만 아니라 다른 ECMAScript 버전에 대한 지원을 활성화하도록 해당 설정을 재정의 할 수 있습니다.

  • ecmaVersion : 사용할 ECMAScript의 버전 (default: 5)
  • sourceType : "script" (default) || "module" (ECMAScript modules 사용 시) 설정
  • ecmaFeatures : 사용하려는 추가적인 언어 기능을 나타내는 객체:
    • globalReturn : 전역 스코프에서 return 사용 허용
    • impliedStrict : 전역 Strict mode 활성화 (ecmaVersion이 5 이상인 경우)
    • jsx : JSX 활성화
{
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true
        }
    }
}

2.2 Parser

ESLint가 어떤 parser를 사용할 것인지 정의합니다.

Parser: Espree (default)

ESLint와 호환되는 parsers:

  • Esprima
  • @babel/eslint-parser
  • @typescript-eslint/parser
{
    "parserOptions": {
        ...
    },
    "parser": "esprima", 
}

2.3 Processor

plugin은 프로세서를 제공 할 수 있습니다.

Processor는 다른 종류의 파일에서 JavaScript 코드를 추출한 다음 ESLint가 JavaScript 코드를 린트하도록 할 수 있습니다.

또는 Processor는 어떤 목적을 위해 전처리 과정(preprocessing)에서 JavaScript 코드를 변환 할 수 있습니다.

  • 구성 파일에서 프로세서를 지정하려면 plugin 이름과 processor 이름이 '/'로 연결된 문자열과 함께 processor key를 사용하십시오.

For example, the following enables the processor a-processor that the plugin a-plugin provided:

{
    "plugins": ["a-plugin"],
    "processor": "a-plugin/a-processor"
}
  • 특정 파일에 대한 processors를 지정할려면 overrideskey 와processorkey의 조합으로 설정해주면 됩니다.

For example, the following uses the processor a-plugin/markdown for *.md files.

{
    "plugins": ["a-plugin"],
    "overrides": [
        {
            "files": ["*.md"],
            "processor": "a-plugin/markdown"
        }
    ]
}

2.4 Environments

Environments는 스크립트가 실행되도록 설계된 환경, 각 환경에는 미리 정의된 특정 전역 변수 세트가 함께 제공됩니다.

Environments는 상호 배타적이지 않기 때문에 한번에 여러개를 선언할 수 있습니다.

즉, 사용자가 어떤 환경(browser, node, mocha, mongo 등)에서 Lint 를 사용할 것인지 정의해준다.

env목록은 env list 여기서 확인할 수 있습니다.

  • .eslintre.json
{
    "env": {
        "browser": true,
        "node": true
    }
}
  • eslintConfigkey in a package.json
{
    "name": "mypackage",
    "version": "0.0.1",
    "eslintConfig": {
        "env": {
            "browser": true,
            "node": true
        }
    }
}

2.5 Globals

no-undef 규칙은 동일한 파일 내에서 사용되었지만 정의되지 않은 변수에 대해 경고합니다.

이 규칙으로 인해 만약 정의되지 않은 전역 변수를 사용하면 ESLint는 해당 전역 변수에 대해 경고를 띄우게 됩니다.

globals는 ESLint 경고가 발생하지 않도록 전역 변수을 정의하는 confiuration key입니다.

globals에 대한 더 많은 정보

globals속성은"writable" 또는 "readonly" 값을 가집니다.

These examples allow "var1" to be overwritten in your code, but disallow it for "var2".

{
    "globals": {
        "var1": "writable",
        "var2": "readonly"
    }
}

2.6 Plugins

ESLint는 third-party plugins을 지원합니다.

plugin은 parser를 사용하여 작성된 rule을 포함하고 있습니다.

npm(or yarn)을 통해 설치합니다.
환경설정파일에서 pluginskey를 사용하여 추가합니다.

{
    "plugins": [
        "eslint-plugin-plugin2",
        "plugin1", // // means eslint-plugin-plugin1
        "@jquery/jquery", // means @jquery/eslint-plugin-jquery
        "@foobar" // means @foobar/eslint-plugin
    ]
}

plugin은 Plugin Naming Convention이 있습니다.
non-scoped packages에서 eslint-plugin 접두사는 생략이 가능합니다.

2.7 Rules

ESLint에는 프로젝트에서 사용하는 rule을 수정할 수 있습니다. rule을 변경하는 경우, 다음과 같은 설정 규칙을 따라야합니다.

  • "off" or 0 - turn the rule off
  • "warn" or 1 - turn the rule on as a warning (doesn't affect exit code)
  • "error" or 2 - turn the rule on as an error (exit code is 1 when triggered)

규칙을 수정하는 방법은 2가지가 있습니다.

  • Using Configuration Comments
/* eslint eqeqeq: "off", curly: "error" */
  • Using Configuration Files
{
    "rules": {
        "eqeqeq": "off",
        "curly": "error",
        "quotes": ["error", "double"]
    }
}

자세한 Configuring은 Configuring ESLint 참고

2.8 Extends

extends은 기존 환경 설정 파일의 규칙에 새로운 규칙(plugin이 가진 규칙)을 추가시켜 확장시키는 key이다.

extends property Value Types

    1. a "string" that specifies a configuration (either a path to a config file, the name of a shareable config, eslint:recommended, or eslint:all)
    1. an "array" of strings : each additional configuration extends the preceding configurations

Using the configuration from a plugin

plugin은 일반적으로 규칙을 내보내는 npm package입니다.

plugins속성 값은 패키지 이름의 eslint-plugin-접두사를 생략할 수 있습니다.

The extends property value can consist of:

  • plugin:
  • the package name (from which you can omit the prefix, for example, react)
    -/
  • the configuration name (for example, recommended)

Example of a configuration file in JSON format:
"plugin:react/recommended"

{
    "plugins": [
        "react"
    ],
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended"
    ],
    "rules": {
       "react/no-set-state": "off"
    }
}

2.9 Ignoring Files and Directories

ESLint가 실행이 되면, 현재 working directory에서 파일들을 lint 하기 전에 .eslintignore 을 찾은 후 lint를 시작합니다.

한 번에 하나의 .eslintignore 파일 만 사용할 수 있으므로 현재 작업 디렉토리에 있는 파일 이외의 .eslintignore 파일은 사용되지 않습니다.

linting하지 않는 2가지 방법이 있습니다.

    1. ignorePatterns in config files

    구성 파일에서 ignorePatterns를 사용하여 ESLint가 특정 파일 및 디렉토리를 무시하도록 지시 할 수 있습니다.

    {
        "ignorePatterns": ["temp.js", "**/vendor/*.js"],
        "rules": {
            //...
        }
    }

Ignoring Files and Directories 더 많은 정보

    1. .eslintignore file in your project's root directory

      .eslintignore파일은 각 line이 linting되지 않는 경로를 나타내는 glob 패턴인 일반 text 파일입니다.

Using eslintIgnore in package.json

.eslintignore 파일이 없고 alternate file (대체 파일)이 지정되지 않은 경우 ESLint는 package.json에서 eslintIgnore key를 찾습니다.

{
  "name": "mypackage",
  "version": "0.0.1",
  "eslintConfig": {
      "env": {
          "browser": true,
          "node": true
      }
  },
  "eslintIgnore": ["hello.js", "world.js"]
}

정리

parser Options : js 버전, 모듈 사용 여부 등 설정

parser : js를 linting하는 도구 정의

proessor : linting 대상 파일에서 js code를 추출한 다음 전처리 과정(preprocessing)에서 js 변환 수행

env : js가 작동할 환경을 설정, 각 환경마다 미리 정의된 전역 변수 세트가 있음

globals : 추가적인 전역 변수 정의

plugins : 규칙을 가진 써드 파티 모듈

rules : 규칙을 정의 extends의 규칙 overriding가능

extends : plugin의 규칙 추가시켜 확장 & 활성화


Reference

ESLint 공식 홈페이지

https://indepth.dev/posts/1282/setting-up-efficient-workflows-with-eslint-prettier-and-typescript

0개의 댓글