React 개발환경 세팅하기(without CRA) - 4. typescript 설치 및 설정

정성욱·2019년 11월 27일
1
  1. src 폴더에 components 폴더 생성

  2. typescript 설치

npm install --save @types/react
npm install --save @types/react-dom
npm install --save-dev typescript
  1. typescript 설정 파일 추가
    root폴더에 tsconfig.json 생성 후 아래 코드 입력
{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react"
    },
    "include": [
        "./src/**/*"
    ]
}
  1. components 폴더에 Hello.tsx 파일 생성
    아래코드 입력
import * as React from "react";
export interface HelloProps { compiler: string; framework: string; }
// 'HelloProps'는 props의 형태을 만듭니다.
// State가 설정되어 있지 않아 '{}'타입을 사용합니다.
export class Hello extends React.Component<HelloProps, {}> {
    render() {
        return <h1>Hello from {this.props.compiler} and {this.props.framework}!</h1>;
    }
}
  1. src폴더의 index.js의 확장자명을 .tsx로 변경
    변경 후, 아래 코드와 같이 Hello 컴포넌트 추가
import * as React from "react";
import * as ReactDOM from "react-dom";
import { Hello } from "./components/Hello";
ReactDOM.render(
    <Hello compiler="TypeScript" framework="React" />,
    document.getElementById("example")
);
  1. babel 추가 설치 및 설정
npm install --save @babel/preset-typescript

.babelrc 파일에 아래 코드 추가

{
	"presets": [
      "@babel/preset-env",
      "@babel/preset-react",
      "@babel/preset-typescript" // <-추가
    ]
}
  1. webpack.config.js 설정 변경
...
module: {
 rules: [
   {
     test: /\.(js|jsx|ts|tsx)$/, // <-<-.ts , .tsx 확장자 추가
     exclude: /node_modules/,
     use: ['babel-loader']
   }
 ]
},
resolve: {
 extensions: ['*', '.js', '.jsx','.ts','.tsx'] // <-.ts , .tsx 확장자 추가
},
...
profile
Show me the code

2개의 댓글

comment-user-thumbnail
2020년 4월 2일

좋은 글 감사드립니다.

답글 달기
comment-user-thumbnail
2020년 9월 1일

많은 도움 되었습니다.

답글 달기