한 입 크기로 잘라먹는 타입스크립트 - 타입스크립트와 리액트 (React With TypeScript)
1. 리액트 앱 설치
section11 폴더를 생성한 뒤, 리액트 앱 설치를 위해 터미널에서 'npx create-react-app .' 명령어를 입력한다.
명령어에서 .의 의미는 새로운 폴더를 생성하지 말고 section11 폴더 아래 리액트 앱을 바로 생성하라는 의미이다.
- Terminal
npx create-react-app .
Creating a new React app in D:\개발\인프런\한 입 크기로 잘라먹는 타입스크립트(TypeScript)\onebite-typescript\section11.
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...
added 1319 packages in 36s
264 packages are looking for funding
run `npm fund` for details
Git repo not initialized Error: Command failed: git --version
at checkExecSyncError (node:child_process:890:11)
at execSync (node:child_process:962:15)
at tryGitInit (D:\개발\인프런\한 입 크기로 잘라먹는 타입스크립트(TypeScript)\onebite-typescript\section11\node_modules\react-scripts\scripts\init.js:46:5)
at module.exports (D:\개발\인프런\한 입 크기로 잘라먹는 타입스크립트(TypeScript)\onebite-typescript\section11\node_modules\react-scripts\scripts\init.js:276:7)
at [eval]:3:14
at runScriptInThisContext (node:internal/vm:144:10)
at node:internal/process/execution:109:14
at [eval]-wrapper:6:24
at runScript (node:internal/process/execution:92:62) {
status: 1,
signal: null,
output: [ null, null, null ],
pid: 5660,
stdout: null,
stderr: null
}
Installing template dependencies using npm...
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: section11@0.1.0
npm ERR! Found: react@19.0.0
npm ERR! node_modules/react
npm ERR! react@"^19.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^18.0.0" from @testing-library/react@13.4.0
npm ERR! node_modules/@testing-library/react
npm ERR! @testing-library/react@"^13.0.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! C:\Users\admin\AppData\Local\npm-cache\_logs\2024-12-26T02_31_05_067Z-eresolve-report.txt
npm ERR! A complete log of this run can be found in: C:\Users\admin\AppData\Local\npm-cache\_logs\2024-12-26T02_31_05_067Z-debug-0.log
`npm install --no-audit --save @testing-library/jest-dom@^5.14.1 @testing-library/react@^13.0.0 @testing-library/user-event@^13.2.1 web-vitals@^2.1.0` failed
라이브러리가 충돌나서 불완전하게 설치되었으므로, section11 폴더 아래 설치된 파일들을 모두 지우고 다시 설치한다.
npm 캐시 초기화 후 cra 글로벌 삭제 및 재설치.
(또다른 해결책 : 'npx create-react-app . --template typescript --legacy-peer-deps')
- Terminal
npm cache clean -f
npm WARN using --force Recommended protections disabled.
npm uninstall -g create-react-app
up to date in 338ms
npx create-react-app my-app
Creating a new React app in D:\개발\인프런\한 입 크기로 잘라먹는 타입스크립트(TypeScript)\onebite-typescript\section11\my-app.
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...
added 1321 packages in 31s
264 packages are looking for funding
run `npm fund` for details
Git repo not initialized Error: Command failed: git --version
at checkExecSyncError (node:child_process:890:11)
at execSync (node:child_process:962:15)
at tryGitInit (D:\개발\인프런\한 입 크기로 잘라먹는 타입스크립트(TypeScript)\onebite-typescript\section11\my-app\node_modules\react-scripts\scripts\init.js:46:5)
at module.exports (D:\개발\인프런\한 입 크기로 잘라먹는 타입스크립트(TypeScript)\onebite-typescript\section11\my-app\node_modules\react-scripts\scripts\init.js:276:7)
at [eval]:3:14
at runScriptInThisContext (node:internal/vm:144:10)
at node:internal/process/execution:109:14
at [eval]-wrapper:6:24
at runScript (node:internal/process/execution:92:62) {
status: 1,
signal: null,
output: [ null, null, null ],
pid: 21224,
stdout: null,
stderr: null
}
Installing template dependencies using npm...
added 40 packages in 3s
268 packages are looking for funding
run `npm fund` for details
Removing template package using npm...
removed 1 package, and audited 1361 packages in 2s
268 packages are looking for funding
run `npm fund` for details
8 vulnerabilities (2 moderate, 6 high)
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.
Success! Created my-app at D:\개발\인프런\한 입 크기로 잘라먹는 타입스크립트(TypeScript)\onebite-typescript\section11\my-app
Inside that directory, you can run several commands:
npm start
Starts the development server.
npm run build
Bundles the app into static files for production.
npm test
Starts the test runner.
npm run eject
Removes this tool and copies build dependencies, configuration files
and scripts into the app directory. If you do this, you can’t go back!
We suggest that you begin by typing:
cd my-app
npm start
Happy hacking!
이렇게 설치 완료. 이후 my-app 폴더에 설치된 폴더 및 파일들을 상위폴더 section11 로 이동시킨 뒤, my-app 폴더는 삭제. section11 폴더가 루트 폴더가 되었다.
이후 package.json 파일에서 'name' 부분 값을 'section11' 로 수정한다.
- package.json
{
"name": "section11",
...
}
생성이 완료되었다면, 타입스크립트 적용 전 불필요한 파일 App.test.js, logo.svg, reportWebVitals.js, setupTests.js 를 제거한다.
index.js 에서도 제거된 파일의 import 를 삭제한다.
- /src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
App.js 에서도 제거된 파일의 import 를 삭제한다.
- /src/App.js
import './App.css';
function App() {
return (
<div className="App"></div>
);
}
export default App;
2. 리액트 앱에 타입스크립트 적용
이제 리액트 앱에 타입스크립트를 적용한다.
타입 선언 패키지들을 추가한다. 리액트앱을 위한 타입 정보들을 제공하는 패키지들을 설치한다.
- Terminal
npm i @types/node @types/react @types/react-dom @types/jest
added 3 packages, changed 1 package, and audited 1364 packages in 2s
268 packages are looking for funding
run `npm fund` for details
8 vulnerabilities (2 moderate, 6 high)
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.
4가지 패키지가 설치되었다.
package.json 의 'dependencies' 에 명시된 설치된 패키지를 확인한다.
- package.json
...
"dependencies": {
...
"@types/jest": "^29.5.14",
"@types/node": "^22.10.2",
"@types/react": "^19.0.2",
"@types/react-dom": "^19.0.2",
...
},
...
node_modules 폴더 아래 @types 폴더를 확인한다. 타입 선언들이 들어있는 것을 확인할 수 있다.
@types/react 를 확인하면 여러가지 리액트가 제공하는 기능들에 대한 타입들이 정의되어 있다.
컴파일러의 옵션을 설정한다. tsconfig.json 파일을 생성하여 설정한다.
'target' 옵션을 'ES5', 'module' 옵션을 'CommonJS' 로 설정하는 이유는, 리액트 앱이 어디서든지 잘 동작할 수 있도록 만들기 위함이다.
- tsconfig.json
{
"compilerOptions": {
"target": "ES5"
, "module": "CommonJS"
, "strict": true
, "allowJs": true
}
, "include": ["src"]
}
이렇게 작성하면 App.js 파일에서 '파일은 입력 파일을 덮어쓰므로 쓸 수 없습니다.' 오류가 발생한다.
타입스크립트는 기본적으로 .js 확장자의 파일로부터 jsx 문법을 해설할 수 없기 때문이다.
따라서 /src 경로의 .js 확장자의 파일을 .jsx 확장자로 바꿔준다.
App.js -> App.jsx
index.js -> index.jsx
tsconfig.json 파일로 이동하면 오류가 사라진다.
이렇게 타입스크립트의 기초 설정이 완료되었다.
3. 자바스크립트로 생성된 프로젝트를 타입스크립트 프로젝트로 변환
이제 .jsx 파일을 타입스크립트 파일로 바꿔 타입 검사를 수행하도록 만들어준다.
자바스크립트로 만들어진 프로젝트를 타입스크립트로 변경시, 개별파일별로 하나씩 바꾸는게 유리하다.
따라서 파일들을 한꺼번에 바꾸지 않고 개별파일별로 하나씩 바꾸며 오류를 해결한다.
1) index.jsx -> index.tsx
- /src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
// const root = ReactDOM.createRoot(document.getElementById('root')!); // non-null 단언
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement); // 단언
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
tsconfig.json 파일에 여러가지 설정을 추가한다.
기본 내보내기 옵션이 없을 때에도 모듈을 불러올 수 있는 설정을 추가한다.
'esModuleInterop' 옵션을 true 로 설정하면, default 로 내보낸 값이 없는 모듈에서도 모듈 불러올 수 있도록 하는 옵션이다.
타입스크립트 컴파일러가 jsx 문법을 해석할 수 있도록 하는 설정을 추가한다.
- tsconfig.json
{
"compilerOptions": {
...
, "esModuleInterop": true
, "jsx": "react-jsx"
}
...
}
2) App.jsx -> App.tsx
- /src/App.tsx
import './App.css';
function App() {
return (
<div className="App"></div>
);
}
export default App;
자바스크립트 프로젝트를 타입스크립트 프로젝트로 마이그레이션하는 과정들을 크게 4가지로 분류하면,
1 단계 : 타입선언 패키지 설치
@types/node @types/react @types/react-dom @types/jest
2 단계 : 컴파일러 옵션 설정
tsconfig.json
3 단계 : 모든 .js 파일 .jsx 파일 확장자로 변경
4 단계 : 개별파일들 하나씩 .tsx 로 수정하며 발생하는 오류 해결
참고링크 : https://www.inflearn.com/course/%ED%95%9C%EC%9E%85-%ED%81%AC%EA%B8%B0-%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8#
한 입 크기로 잘라먹는 타입스크립트(TypeScript) 강의 | 이정환 Winterlood - 인프런
이정환 Winterlood | 문법을 넘어 동작 원리와 개념 이해까지 배워도 배워도 헷갈리는 타입스크립트 이제 제대로 배워보세요! 여러분을 타입스크립트 마법사🧙🏻♀️로 만들어드립니다., 프론
www.inflearn.com
'강의 실습 > 한 입 크기로 잘라먹는 타입스크립트(TypeScript)' 카테고리의 다른 글
상태관리와 Props 2 (1) | 2024.12.28 |
---|---|
상태관리와 Props 1 (1) | 2024.12.27 |
조건부 타입 기반의 유틸리티 타입 - Exclude, Extract, ReturnType (1) | 2024.12.25 |
맵드 타입 기반의 유틸리티 타입 2 - Pick, Omit, Record (0) | 2024.12.24 |
맵드 타입 기반의 유틸리티 타입 1 - Partial, Required, Readonly (0) | 2024.12.23 |
댓글