已有项目引入TS,16.6 React和antdpro脚手架搭建

81 阅读1分钟

Situation

上手学习TypeScript,想到在已有项目中引入TypeScript重构几个页面,增加对TypeScript使用的印象,项目使用antdpro脚手架搭建,React版本为16.6

Task

在已有项目中引入TypeScript,利用TS重构几个页面

Action

配置TypeScript

1、安装TypeScript

npm install typescript --save-dev

2、初始化tsconfig配置文件,默认在项目根目录生成tsconfig.json文件

npx tsc --init

3、配置tsconfig.json,更多的配置可查看TypeScript官网文档

写些代码

参考TypeScript官方实例,添加代码验证TypeScript是否引入成功

1、编写Hello.tsx组件,代码如下

import React from "react";

export interface HelloProps {
  compiler: string;
  framework: string;
}

export class Hello extends React.Component<HelloProps, {}> {
  render() {
    return (
      <div>
        <h1>Hello from {this.props.compiler} and {this.props.framework}!</h1>
      </div>
    );
  }
}

2、页面引入Hello.tsx组件并使用

import {Hello} from "@/components/Hello";
render(){
return (
  <div>
    <Hello compiler='TypeScript' framework='React'/>
  </div>
);
}

3、渲染效果

image.png

Result

成功在已有项目引入TypeScript,接下来就可以愉快地用TS编写代码了~

若有不当,肯定斧正