建议:项目复杂的情况下,建议推翻项目重构,而不要在已有项目中集成ts
一、已有项目,中途或者翻新需要集成ts
(一)操作
官方文档:https://create-react-app.dev/docs/adding-typescript/
1、安装包:
yarn add typescript @types/node @types/react @types/react-dom
@types/jest
2、新建tsconfig.json,复制一下内容
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}
3、在src下新建react-app-env.d.ts,复制一下内容
///
4、重启运行并测试
import React from 'react'
type Props = {
name:string}
export default function Home() {
return (
<div>
首页
<Sub name="ttt"/>
</div>
)
}
const Sub=({
name}:Props)=>{
return(
<div>{
name}</div>
)
}
(二)遇到的问题
1、TypeScript 引入第三方包,报无法找到模块“XXX”的声明文件错误
解决:
(1)按照提示安装,失败,若成功就推荐使用此方法
npm install -D @types/react-router-dom
or
yarn add -D @types/react-router-dom
(2)自定义类型
->在项目根目录新建 typings 文件夹。 在 typings 文件夹下的 react-router-dom.d.ts 文件
declare module 'react-router-dom' {
const content: any
export = content
}
->在 tsconfig.json 里的 include 添加上 typings
二、新项目,在搭建时候集成ts
react脚手架工具create-react-app默认支出ts,创建支持ts的react项目命令
npx create-react-app 项目名称 --template typescript
(一)与react项目的区别
1、项目根目录中增加了tsconfig.json配置文件:指定TS的编译选项(编译时是否移除注释)
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",