TypeScript를 React와 함께 사용하기
소개
TypeScript는 굉장합니다. 리액트도 마찬가지입니다. 둘 다 함께 사용합시다! TypeScript를 사용하면 IntelliSense의 이점을 얻을 수 있을 뿐만 아니라 코드에 대한 추가 추론 기능을 얻을 수 있습니다. 뿐만 아니라 TypeScript를 채택하면 마찰이 적습니다. 프로젝트의 나머지 부분에서 문제를 일으키지 않고 파일을 점진적으로 업그레이드할 수 있기 때문입니다.
전제 조건
이 가이드를 따르려면 다음이 필요합니다.
sudo
권한이 있고 방화벽이 활성화된 루트가 아닌 사용자로 설정된 Ubuntu 20.04 서버 1개. Ubuntu 20.04 초기 서버 설정 가이드에 따라 이를 수행할 수 있습니다.- Node.js 및
npm
이 설치되었습니다. NodeSource PPA를 사용하여 Apt로 이 작업을 수행할 수 있습니다. 시작하려면 Ubuntu 20.04에 Node.js를 설치하는 방법에 대한 가이드의 옵션 2를 따르세요.
프로젝트 설정:
전제 조건 가이드를 따르고 Node.js 및 npm
을 설치했다고 가정하고 새 디렉터리를 생성하는 것으로 시작합니다. 여기서는 react-typescript
라고 하겠습니다.
- mkdir react-typescript
터미널 내에서 다음 디렉터리로 변경합니다.
- cd react-typescript/
그런 다음 기본값으로 새 npm
프로젝트를 초기화합니다.
- npm init -y
OutputWrote to /home/sammy/react-typescript/package.json:
{
"name": "react-typescript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
이것이 초기화되면 다음으로 적절한 React 종속성을 설치합니다.
React 종속성 설치
먼저 React 종속성 react
및 react-dom
을 설치합니다.
- sudo npm install react react-dom
다음으로 src
라는 폴더를 만듭니다.
- mkdir src
해당 src
디렉토리로 변경합니다.
- cd src/
그런 다음 index.html
파일을 만들어 src
폴더에 삽입합니다. 원하는 텍스트 편집기를 사용하여 이 작업을 수행할 수 있습니다. 여기서는 nano
를 사용합니다.
- nano index.html
이제 index.html
파일이 열렸으므로 일부 내용을 수정하고 다음 콘텐츠를 추가할 수 있습니다.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>React + TypeScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="main"></div>
<script type="module" src="./App.tsx"></script>
</body>
</html>
완료되면 파일을 저장하고 닫습니다. nano
를 사용하는 경우 CTRL + X
를 누른 다음 Y
및 ENTER
를 눌러 이 작업을 수행할 수 있습니다.
Create React App 사용을 선호하는 경우 이 섹션을 사용할 것입니다. 먼저 Parcel을 설치하여 프로젝트에 추가해 보겠습니다.
- sudo npm install parcel
다음으로 Typescript를 설치합니다.
- sudo npm install --location=global typescript
그런 다음 React 및 ReactDOM용 유형을 설치합니다.
- sudo npm install @types/react @types/react-dom
모든 것이 설치된 후 마침표 두 개를 사용하여 상위 디렉토리로 돌아갑니다.
- cd ..
개발 서버 시작 및 실행
다음으로 개발 서버를 시작할 새 작업으로 package.json
을 업데이트합니다. 먼저 원하는 텍스트 편집기로 파일을 만들고 열면 됩니다.
- nano package.json
파일을 연 후 기존 콘텐츠를 다음으로 바꿉니다.
{
"name": "react-typescript",
"version": "1.0.0",
"description": "An example of how to use React and TypeScript with Parcel",
"scripts": {
"dev": "parcel src/index.html"
},
"keywords": [],
"author": "Paul Halliday",
"license": "MIT"
}
완료되면 파일을 저장하고 닫습니다.
이제 src
디렉토리로 다시 변경합니다.
- cd src/
디렉터리에 있으면 기본 카운터가 포함된 Counter.tsx
파일을 만들고 엽니다.
- nano Counter.tsx
파일에 다음 콘텐츠를 추가합니다.
import * as React from 'react';
export default class Counter extends React.Component {
state = {
count: 0
};
increment = () => {
this.setState({
count: (this.state.count + 1)
});
};
decrement = () => {
this.setState({
count: (this.state.count - 1)
});
};
render () {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.increment}>Increment</button>
<button onClick={this.decrement}>Decrement</button>
</div>
);
}
}
완료되면 파일을 저장하고 닫습니다.
그런 다음 원하는 텍스트 편집기로 App.tsx
파일을 만듭니다.
- nano App.tsx
이제 파일이 열렸으므로 다음 정보를 추가하여 카운터를 로드합니다.
import * as React from 'react';
import { render } from 'react-dom';
import Counter from './Counter';
render(<Counter />, document.getElementById('main'));
콘텐츠를 추가했으면 파일을 저장하고 닫습니다.
그런 다음 1234
에 대한 포트 트래픽을 허용하도록 방화벽 권한을 업데이트합니다.
- sudo ufw allow 1234
마지막으로 다음 명령을 사용하여 프로젝트를 실행합니다.
- sudo npm run dev
Output
> react-typescript@1.0.0 dev
> parcel src/index.html
Server running at http://localhost:1234
✨ Built in 3.84s
브라우저에서 http://your_domain_or_IP_server:1234
로 이동하여 모든 것이 작동하는지 확인합니다. 페이지에 다음과 같은 증가 및 감소 기능이 있어야 합니다.
이제 샘플 프로젝트가 성공적으로 실행되고 있습니다.
React 앱 및 TypeScript 만들기
즉시 사용할 수 있습니다.
create-react-app
명령을 호출할 때 --typescript
플래그를 사용하십시오.
기능성 부품
Stateless 또는 기능적 구성 요소는 TypeScript에서 다음과 같이 정의할 수 있습니다.
import * as React from 'react';
const Count: React.FunctionComponent<{
count: number;
}> = (props) => {
return <h1>{props.count}</h1>;
};
export default Count;
우리는 React.FunctionComponent
를 사용하고 예상되는 소품의 객체 구조를 정의하고 있습니다. 이 시나리오에서는 count
라는 단일 소품으로 전달될 것으로 예상하고 이를 인라인으로 정의합니다. Props
와 같은 인터페이스를 생성하여 다른 방식으로 정의할 수도 있습니다.
interface Props {
count: number;
}
const Count: React.FunctionComponent<Props> = (props) => {
return <h1>{props.count}</h1>;
};
클래스 구성요소
클래스 구성 요소는 다음과 같이 TypeScript에서 유사하게 정의할 수 있습니다.
import * as React from 'react';
import Count from './Count';
interface Props {}
interface State {
count: number;
};
export default class Counter extends React.Component<Props, State> {
state: State = {
count: 0
};
increment = () => {
this.setState({
count: (this.state.count + 1)
});
};
decrement = () => {
this.setState({
count: (this.state.count - 1)
});
};
render () {
return (
<div>
<Count count={this.state.count} />
<button onClick={this.increment}>Increment</button>
<button onClick={this.decrement}>Decrement</button>
</div>
);
}
}
기본 소품
기본 소품을 설정하려는 시나리오에서 defaultProps
를 정의할 수도 있습니다. Count 예제를 업데이트하여 다음을 반영할 수 있습니다.
import * as React from 'react';
interface Props {
count?: number;
}
export default class Count extends React.Component<Props> {
static defaultProps: Props = {
count: 10
};
render () {
return <h1>{this.props.count}</h1>;
}
}
Counter
구성 요소에 대한 this.state.count
전달도 중지해야 합니다. 이렇게 하면 기본 소품을 덮어쓰게 됩니다.
render () {
return (
<div>
<Count />
<button onClick={this.increment}>Increment</button>
<button onClick={this.decrement}>Decrement</button>
</div>
)
}
이제 TypeScript 및 React를 사용하도록 설정된 프로젝트와 고유한 기능 및 클래스 기반 구성 요소를 만드는 도구가 있어야 합니다!