vscode로 리액트 타입스트립트 프로젝트 만들기1 - 셋팅 설정파일들 package.json, .eslintrc.js, tsconfig.json, prettierrc.js, reportWebVitals.ts
내가 현재쓰는 버전
1. 프로젝트 생성 및 초기 설정
npx create-react-app my-app --template typescript
cd my-app
npm install react@18 react-dom@18
간혹 프로젝트 생성 후 web-vitals 모듈이 누락된 경우 아래 명령어로 설치 하면된다.
npm install web-vitals
2. 필요한 패키지 설치
npm install react-router-dom@^7.1.5 web-vitals styled-components @types/styled-components
npm install @eslint/config-array @eslint/object-schema eslint-config-prettier eslint-plugin-prettier prettier
npm install @typescript-eslint/eslint-plugin @typescript-eslint/parser --save-dev
npm install @testing-library/jest-dom @testing-library/react @types/jest @types/react @types/react-dom --save-dev
3. package.json 설정
react-scripts 버전과 관련하여 react-scripts가 typescript@^4.9.5와 호환되지 않아서 문제가 발생할 수 있습니다. 이를 해결하려면 react-scripts를 최신 버전으로 업데이트하거나 typescript 버전을 4.x로 맞추는 것이 좋습니다.
현재 typescript는 ^5.x로 설정되어 있기 때문에, 버전 충돌이 발생할 수 있습니다. 이를 해결하려면 typescript를 4.x로 맞추세요.
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^7.1.5",
"react-scripts": "^5.0.1",
"web-vitals": "^4.2.4",
"styled-components": "^5.3.3",
"@types/styled-components": "^5.1.34"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"eslint": "^8.57.1",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.3",
"prettier": "^3.4.2",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0",
"@types/jest": "^29.5.14",
"@types/react": "^19.0.8",
"@types/react-dom": "^19.0.3",
"typescript": "^4.9.5"
}
4. eslint 및 prettier 설정
.eslintrc.js
**Eslint 검사 및 자동수정 ( src 폴더 하위의 JS/TS 파일 전체 검사)
npx eslint "src/**/*.{js,ts,jsx,tsx}" --fix
module.exports = {
parser: '@typescript-eslint/parser',
extends: ['plugin:react/recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],
plugins: ['prettier'], // Prettier 플러그인 활성화
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
rules: {
'prettier/prettier': 'error', // Prettier 오류를 ESLint 오류로 표시
'@typescript-eslint/no-unused-vars': 'off', // 미사용 변수에 대한 경고 표시-warn
'react/prop-types': 'off', // prop-types 규칙 비활성화 (TypeScript에서는 굳이 필요하지 않음)
'react/jsx-wrap-multilines': 0, // 0 = off, 1 = warn, 2 = error
},
settings: {
react: {
version: 'detect',
},
},
};
prettier.config.js
✅ Prettier 포맷팅 실행 ( Prettier는 포맷팅에 집중하므로 코드 스타일 정리에 유용)
npx prettier --write "src/**/*.{js,ts,jsx,tsx,json,css,scss,md}"
module.exports = {
printWidth: 120,
tabWidth: 2,
useTabs: false,
semi: true,
singleQuote: true,
quoteProps: "consistent",
trailingComma: "es5",
bracketSpacing: true,
endOfLine: "crlf",
htmlWhitespaceSensitivity: "css",
bracketSameLine: true,
jsxSingleQuote: false,
proseWrap: "preserve",
};
✅ 추천 스크립트 설정 (package.json)
"scripts": {
"lint": "eslint \"src/**/*.{js,ts,jsx,tsx}\"",
"lint:fix": "eslint \"src/**/*.{js,ts,jsx,tsx}\" --fix",
"format": "prettier --write \"src/**/*.{js,ts,jsx,tsx,json,css,scss,md}\""
}
이렇게 설정하면 아래처럼 간단히 실행할 수 있다
npm run lint:fix
npm run format
5. tsconfig.json 설정
{
"compilerOptions": {
"target": "ES6",
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve"
},
"include": [
"src",
"src/**/*.svg",
".eslintrc.js"
]
}
"jsx": "react-jsx"
[ reportWebVitals.ts ] - 이 부분을 꼭 변경해야 오류가 사라진다❗❗❗
import { onCLS, onFID, onFCP, onLCP, onTTFB } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: (metric: any) => void) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
onCLS(onPerfEntry);
onFID(onPerfEntry);
onFCP(onPerfEntry);
onLCP(onPerfEntry);
onTTFB(onPerfEntry);
}
};
export default reportWebVitals;
6. 충돌/중복된 부분 - feat 쳇gpt
- typescript 버전 충돌: 현재 typescript를 5.x 버전으로 설정해두었는데, react-scripts@5.0.1은 typescript@^4.x와 호환됩니다. typescript를 ^4.x로 다운그레이드하거나, react-scripts를 최신 버전으로 업데이트하는 것이 필요합니다.
- eslint와 prettier: eslint-config-prettier와 eslint-plugin-prettier를 함께 사용하면, ESLint에서 prettier 규칙을 충족하지 않는 코드를 오류로 표시합니다. 이를 통해 코드 스타일을 강제할 수 있습니다.
- 불필요한 @types 패키지: @types/react, @types/react-dom 등의 패키지는 이미 create-react-app에서 기본적으로 제공하므로, 이 패키지를 중복 설치할 필요는 없습니다.
7. 추가적인 오류 해결 방법
# 의존성 충돌 해결을 위한 명령어
npm install --legacy-peer-deps
이 명령어를 사용하면 이전 버전의 의존성 규칙을 적용하여 충돌을 피할 수 있다.
개행 오류 lf -> crlf 변경
1. 전체 파일 CRLF로 변환
2. settings.json에 추가
3. 프로젝트 생성 전에 Git 설정 변경
터미널에서 아래 명령어 실행
4. src 폴더 안에 스크립트 파일을 생성
이름은 src/fixEOL.js 또는 src/fixEOL.ts
[ TypeScript (fixEOL.ts) ]
import fs from "fs";
import path from "path";
const changeEOL = (dir: string) => {
fs.readdirSync(dir).forEach((file) => {
const fullPath = path.join(dir, file);
if (fs.statSync(fullPath).isDirectory()) {
changeEOL(fullPath);
} else if (file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") || file.endsWith(".jsx")) {
const content = fs.readFileSync(fullPath, "utf8").replace(/\n/g, "\r\n");
fs.writeFileSync(fullPath, content, "utf8");
console.log(`✅ Converted: ${fullPath}`);
}
});
};
changeEOL(path.join(__dirname, "..", "src"));
실행방법 : npx ts-node src/fixEOL.ts
📌 설명
- src 폴더 내부의 .ts, .tsx, .js, .jsx 파일을 찾음
- LF (\n) → CRLF (\r\n)로 변환
- 변환된 파일 경로를 콘솔에 출력
💡 JavaScript (fixEOL.js)
const fs = require("fs");
const path = require("path");
const changeEOL = (dir) => {
fs.readdirSync(dir).forEach((file) => {
const fullPath = path.join(dir, file);
if (fs.statSync(fullPath).isDirectory()) {
changeEOL(fullPath);
} else if (file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") || file.endsWith(".jsx")) {
const content = fs.readFileSync(fullPath, "utf8").replace(/\n/g, "\r\n");
fs.writeFileSync(fullPath, content, "utf8");
console.log(`✅ Converted: ${fullPath}`);
}
});
};
changeEOL(path.join(__dirname, "..", "src"));
실행 방법 : node src/fixEOL.js # JavaScript 버전
TypeScript와 같은 기능이며, 차이점은 import 대신 require 사용
참고 쳇gpt
기억 휘발 방지용 개인 기록 블로그 입니다. 설정 패키지는 쳇지피티가 잘 압니다.