개발자를 희망하는 초보의 자기개발 이야기

[환경설정] npm을 사용한 Create React App 및 TypeScript 추가 설치 후 에러 해결 과정 본문

프론트엔드(Front-end)/React

[환경설정] npm을 사용한 Create React App 및 TypeScript 추가 설치 후 에러 해결 과정

클라우드아실 2025. 1. 25. 04:28
반응형

React 프로젝트를 시작하면서 npm을 사용하여 create-react-app을 생성하고 의존성 관련 에러를 해결했다. 하지만 TypeScript를 기본적으로 포함시키기 위해 --template typescript 옵션을 추가했어야 하나 잊어버려서 별도의 설치 후 발생한 에러를 해결한 내용이다.

TypeScript 추가 설치

CRA로 리액트를 설치할 때 --template typescript 옵션을 넣지 않았다면 별도로 설치해주어야 한다.

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

Module not found 에러

이후 npm start를 실행했을 때 다음과 같은 모듈을 찾을 수 없다는 에러가 발생했다.

ERROR in ./src/index.tsx 7:0-24
Module not found: Error: Can't resolve './App' in 'D:\work\my-app\src'
ERROR in ./src/index.tsx 8:0-48
Module not found: Error: Can't resolve './reportWebVitals' in 'D:\work\my-app\src'

src/reportWebVitals.ts 파일 수정:

import { Metric } from "web-vitals";

type ReportHandler = (metric: Metric) => void;

const reportWebVitals = (onPerfEntry?: ReportHandler) => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
    import("web-vitals").then(({ onCLS, onFID, onFCP, onLCP, onTTFB }) => {
      onCLS(onPerfEntry);
      onFID(onPerfEntry);
      onFCP(onPerfEntry);
      onLCP(onPerfEntry);
      onTTFB(onPerfEntry);
    });
  }
};

export default reportWebVitals;
  • 설치시 getCLS 같은 함수명을 최신 API에 맞게 onCLS와 같이 수정해야 한다.
  • Metric을 import하고 ReportHandler의 타입을 지정 한다. 

as HTMLElement 사용 :

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
  • 설치시 getCLS 같은 함수명을 최신 API에 맞게 onCLS와 같이 수정해야 한다.
  • Metric을 import하고 ReportHandler의 타입을 지정 한다. 

tsconfig.json 생성 :

{
  "compilerOptions": {
    "target": "ES6",
    "lib": ["DOM", "ES6", "DOM.Iterable", "ScriptHost"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx"
  },
  "include": ["src"]
}
  • 설치시 getCLS 같은 함수명을 최신 API에 맞게 onCLS와 같이 수정해야 한다.
  • Metric을 import하고 ReportHandler의 타입을 지정 한다. 
 

Cannot find module './logo.svg' 에러 해결

이 문제는 TypeScript가 .svg 파일을 모듈로 인식하지 못하기 때문에 발생한다.

react-app-env.d.ts 추가 :

src/react-app-env.d.ts 파일을 생성하고 아래 내용을 추가한다.

/// <reference types="react-scripts" />
반응형