사소한 개발지식/React

React - CRA 없이 React 환경 설정 #2 (ESLint + Prettier)

KimBY 2023. 11. 1. 22:12
728x90
반응형

React

React - CRA 없이 React 환경 설정

🔎 ESLint 설치

ESLint 란 ES(EcmaScript - 표준 JavaScript) 와 Lint의 합성어로 JavaScript 코드에 에러가 있는 부분에 표시를 달아주는 모듈을 말한다. 기본적인 문법 뿐만 아니라 코딩 스타일도 설정 가능하기 때문에 협업에 매우 유용하다.

npm install -D eslint

 

eslint 모듈을 설치한 후 .eslintrc.json (eslint 설정파일)을 만들어야하는데 npx 명령어를 통해 설치도 가능하고 직접 파일을 생성해도 된다. 이번에는 npx 명령어를 통해 생성해보았다.

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

? How would you like to use ESLint? … 
  To check syntax only
❯ To check syntax and find problems
  To check syntax, find problems, and enforce code style
  
? What type of modules does your project use? … 
❯ JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these
  
? Which framework does your project use? … 
❯ React
  Vue.js
  None of these
  
? Does your project use TypeScript? › No / Yes v

? Where does your code run?
✔ Browser
  Node
  
? What format do you want your config file to be in? … 
  JavaScript
  YAML
❯ JSON

eslint-plugin-react@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
? Would you like to install them now? › No / Yes v

? Which package manager do you want to use? … 
❯ npm
  yarn
  pnpm
// .eslintrc.json
{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:react/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["@typescript-eslint", "react"],
  "rules": {
    // eslint 룰을 설정하는 부분
    // 처음엔 비어있고 직접 추가한 부분
    "react/react-in-jsx-scope": "off",
    "no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars": ["warn"],
    "@typescript-eslint/no-explicit-any": ["off"], // any 설정에 대한 체크끔
    "@typescript-eslint/no-namespace": "off"
  }
}

rules 에 관한 자세한 내용은 아래 링크에서 확인 가능하다.

 

Rules Reference - ESLint - Pluggable JavaScript Linter

A pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.

eslint.org

 

// package.json
{
  ...
  "scripts": {
    "dev": "webpack-dev-server --mode development --open --hot",
    "build": "webpack --mode production",
    "lint": "eslint ."
  },
  ...
}
npm run lint

// error
'React' must be in scope when using JSX  react/react-in-jsx-scope

package.json 에 eslint 검사를 할 수 있는 script 를 추가하고 실행하면 jsx(tsx) 파일에서 React 모듈을 import 해야한다는 내용의 에러가 발생한다. 모든 jsx(tsx) 파일마다 최상단에 React 를 import 하면 해결되지만.. 생략하고 싶기 때문에 .eslintrc.json 에 설정을 추가해보자.

// .eslintrc.json
{
  ...,
  "settings": {
    "react": {
      "version": "detect"
    }
  }
}

위 설정을 추가하고 다시 lint 스크립트를 실행하면 문제없이 검사가 끝나게 된다.

 

🔎 Prettier 설치

Prettier 란 코드포맷터로 코딩 형식을 정의하고 규칙에 맞도록 코드를 유지시켜주는 모듈이다. eslint와 함께 협업에서 필수적으로 사용된다.

npm i -D prettier eslint-config-prettier eslint-plugin-prettier
// .eslintrc.json
{
  ...,
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:react/recommended",
    "plugin:prettier/recommended" // 추가
  ],
  ...,
  "rules": {
    "react/react-in-jsx-scope": "off",
    "no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars": ["warn"],
    "@typescript-eslint/no-explicit-any": ["off"], // any 설정에 대한 체크끔
    "@typescript-eslint/no-namespace": "off",
    // 추가
    "prettier/prettier": [
      "error",
      {
        "endOfLine": "auto"
      }
    ]
  },
  ...
}
// .prettierrc
{
  "arrowParens": "always",
  "bracketSameLine": false,
  "bracketSpacing": true,
  "embeddedLanguageFormatting": "auto",
  "htmlWhitespaceSensitivity": "css",
  "insertPragma": false,
  "jsxSingleQuote": true,
  "printWidth": 80,
  "proseWrap": "always",
  "quoteProps": "as-needed",
  "requirePragma": false,
  "semi": true,
  "singleAttributePerLine": false,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "es5",
  "useTabs": false,
  "vueIndentScriptAndStyle": false,
  "endOfLine": "auto"
}

prettier와 eslint 와 prettier 를 같이 사용하기 위한 plugin 을 설치해주고 .eslintrc.json 수정, .prettierrc 파일을 생성해주면 prettierrc 설정이 완료된다. .prettierrc 에 대한 설정은 아래 링크에서 자세히 확인 가능하다.

 

Prettier · Opinionated Code Formatter

Opinionated Code Formatter

prettier.io

이렇게 설정하고 VSCode 에서 코드를 작성 후 저장하게 되면 prettier 설정에 맞게 코드가 자동으로 수정되어야 하지만 아무 수정이 없을 수 있다. 이는 VSCode 에서 Prettier 에 대한 설정을 안 해주었기 때문이다. 

 

🔎 VSCode 에서 Prettier 설정

VSCode 설정 열기
Format On Save 체크

// Ctrl + Shift + p > setting.json
{
  ...,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll": true
  }
}

 

🔎 결과화면

위에 설정까지 다 한 후에 자동저장 시 prettier 가 잘 동작하는지 테스트를 진행하였다.

// index.tsx

// 세미콜론, render 내부 줄바꿈 수정
import { createRoot } from 'react-dom/client'

const container = document.getElementById('root')
const root = createRoot(container as Element)

root.render(
  <div>
    Hello World
  </div>
)


// 저장 후 자동 변경된 코드
import { createRoot } from 'react-dom/client';

const container = document.getElementById('root');
const root = createRoot(container as Element);

root.render(<div>Hello World</div>);
728x90
반응형