npx create-next-app@latest my-app --typescript --eslint
eslint.config.mjs
)import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [...compat.extends("next/core-web-vitals", "next/typescript")];
export default eslintConfig;
npm install -D @typescript-eslint/eslint-plugin @typescript-eslint/parser
npm install -D prettier
eslint는 linting 기능을, prettier는 formatting을 담당하는 구조가 이상적이다. 하지만 eslint에는 일부 formatting 관련된 rule도 포함되어 있다.
이 rule들이 prettier와 다른 설정을 가지고 있다면 설정 충돌이 발생할 수 있으므로 eslint에서 formatting 관련 rule들을 모두 해제해야 할 필요가 있다. 이를 수동으로 진행할 수도 있지만 이를 적용해 주는 eslint plugin인 eslint-config-prettier
가 존재하는데 불필요하거나 prettier와 충돌할 수 있는 모든 규칙을 비활성화해준다.
npm install -D eslint-config-prettier
npm install -D eslint-plugin-import
eslint에서 기본적으로 제공되지 않는 특정 환경을 위한 rule들을 추가하고 싶을 경우에는 plugin을 이용할 수 있다.
확장자 없이 설정하면 주석을 달 수 있다.
{
"env": {
"es6": true
},
"extends": ["react-app", "eslint:recommended", "prettier"],
"rules": {
"no-var": "error", // var 금지
"no-multiple-empty-lines": "error", // 여러 줄 공백 금지
"no-console": ["warn", { "allow": ["warn", "error", "info"] }], // console.log() 경고
"eqeqeq": "error", // 일치 연산자 사용 필수
"dot-notation": "error", // 가능하다면 dot notation 사용
"no-unused-vars": "warn" // 사용하지 않는 변수가 있을 시 경고
}
}
lint: eslint --cache .
와 같이 설정해주면 npm run lint
커맨드로 terminal에서 eslint를 실행시킬 수 있다. 그러나 cache된 파일이 저장된 장소인 eslintcache 파일이 생성되게 되는데 이 파일을 ignore 처리해주어야 다른 사람들과 conflict를 방지할 수 있다.prettier는 프로젝트의 루트 디렉토리에 .prettierrc.확장자
파일을 통해서 설정을 할 수 있다.
설정파일의 확장자 형식은 다양하게 지원하고 있다. (JSON, YAML, JS, TOML)
// .js로 생성하는 이유 = 주석의 용이성을 위함
module.exports = {
// 문자열은 작은 따옴표로 통일 (jsx는 이 설정을 무시함)
singleQuote: true,
// jsx에서 문자열은 작은 따옴표로 통일
jsxSingleQuote: true,
// 코드 마지막에 세미콜론 자동 완성
semi: true,
// 한 줄 최대 문자 수
printWidth: 100,
// 탭 사용을 금지하고 스페이스바 사용을 대체
useTabs: false,
// 들여쓰기 시 탭 너비
tabWidth: 2,
// 객체나 배열 키 : 값 뒤에 콤마 생성
trailingComma: "all",
// 화살표 함수가 하나의 매개변수를 받을 때 괄호 생략
arrowParens: "always",
// JSX의 닫는 괄호를 줄바꿈 하지 않을 것인지 여부
jsxBraketSameLine: "false",
};
format: prettier --write --cache .
와 같이 설정해주면 npm run format
커맨드로 terminal에서 prettier를 실행시킬 수 있다.eslint-plugin-import
를 사용하여 import 문을 그룹별로 분류하고 자동 정렬한다.import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
import importPlugin from "eslint-plugin-import";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
{
plugins: {
import: importPlugin,
},
rules: {
"import/order": [
"error",
{
groups: ["builtin", "external", "internal"],
pathGroups: [
{
pattern: "{next/**,react}",
group: "external",
position: "after",
},
],
pathGroupsExcludedImportTypes: [],
"newlines-between": "always",
alphabetize: {
order: "asc",
caseInsensitive: true,
},
},
],
},
},
];
export default eslintConfig;
groups
: import 그룹의 순서를 정의 (builtin → external → internal → parent → sibling → index)pathGroups
: 특정 패턴의 import를 별도 그룹으로 분류react
: React를 다른 외부 패키지보다 먼저 importnext/**
: Next.js 관련 패키지를 별도로 그룹화@/**
: 프로젝트 내부 경로를 internal 그룹으로 처리pathGroupsExcludedImportTypes
: pathGroups 설정이 적용될 import 타입 정의newlines-between
: 각 그룹 사이에 빈 줄 추가alphabetize
: 각 그룹 내에서 알파벳 순 정렬 (대소문자 구분 안함)import React from "react";
import { PropTypes } from "prop-types";
import styled from "styled-components";
import Image from "next/image";
import Link from "next/link";
import ErrorImg from "@/assets/images/error.png";
import colors from "@/styles/colors";
npm run lint
npm run lint -- --fix
# 전체 파일 ESLint 검사만
npm run lint
# 전체 파일 ESLint 검사 + 자동 수정
npm run lint -- --fix
# 전체 파일 Prettier 포맷팅 적용 (파일 수정됨)
npm run format
# 전체 파일 Prettier 규칙 검사만 (파일 수정 안됨)
npm run format:check
# 특정 파일에만 ESLint 적용
npx eslint src/components/Header.tsx --fix
# 특정 폴더에만 ESLint 적용
npx eslint src/components/ --fix
# 특정 파일에만 Prettier 적용
npx prettier --write src/components/Header.tsx
# 특정 폴더에만 Prettier 적용
npx prettier --write src/components/
# 전체 프로젝트에 포맷팅 + 린팅 한 번에 적용
npm run format && npm run lint -- --fix
# 커밋 전 코드 검사 (파일 수정 없이)
npm run format:check && npm run lint
{
"scripts": {
"lint": "next lint",
"format": "prettier --write .",
"format:check": "prettier --check ."
}
}
# 코드 작성 후 정리
npm run format && npm run lint -- --fix
# 코드 품질 검사
npm run format:check && npm run lint
# 자동화된 검사 (파일 수정 없이)
npm run format:check
npm run lint
.vscode/settings.json
){
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
# 설치
npm install --save-dev husky lint-staged
# package.json에 추가
{
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"prettier --write",
"eslint --fix",
"git add"
]
}
}
--cache
옵션으로 성능 향상 가능{
"scripts": {
"code-check": "npm run format:check && npm run lint",
"code-fix": "npm run format && npm run lint -- --fix",
"pre-commit": "lint-staged"
}
}
참고