react项目集成typescript

本文详细介绍了如何在已有React项目中集成TypeScript,包括安装依赖、配置tsconfig.json和解决引入第三方包的声明文件问题。同时,文章对比了新项目集成TS的区别,并探讨了函数组件和类组件在TypeScript环境下的使用,包括属性类型、默认值和事件处理。
摘要由CSDN通过智能技术生成

建议:项目复杂的情况下,建议推翻项目重构,而不要在已有项目中集成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",
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值