creat-react-app引入typescript

creat-react-app引入typescript

  • 安装typescript相关开发依赖

    npm install --save @types/react @types/react-dom 
    

    使用@types/前缀表示我们要额外获取reactreact-dom的声明文件,可以像品势引入一样,不安装这两个依赖,导入方式是这个样子的

    impore * as React from 'react'
    import * as ReactDOM from 'react-dom'
    
  • 安装开发依赖

    npm install typescript awesome-typescript-loader source-map-loader -D
    

    这些依赖可以使得typescriptwebpack更好的工作。awesome-typescript-loader可以让webpack使用typescript的标准配置文件tsconfig.json编译typescript代码,source-map-loader主要是打包后方便调试

  • 配置tsconfig.json

    {
      "compilerOptions": {
        "jsx": "react",
        "module": "commonjs",
        "declaration": true,
        "noImplicitAny": false,
        "removeComments": true,
        "noLib": false,
        "allowJs": true,
        "strict": true,
        "moduleResolution": "node",
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "strictNullChecks": true,
        "target": "es2015",
        "resolveJsonModule": true,
        "outDir": "./dist",
        "baseUrl": "./src",
        "lib": [
          "es5",
          "es2015",
          "es2017",
          "dom"
        ]
      },
      "include": [
        "src/**/*"
      ],
      "exclude": [
        "node_modules",
        "**/*.spec.ts"
      ]
    }
    
    
  • webpack配置修改

       {
            test: /\.ts|tsx$/, //ts-loader必须在其他处理.js的加载器之前运行
            use: 'awesome-typescript-loader'//之前安装的是ts-loader 导致模块导出的时候报错exports is no defined,在这里替换掉
          },
          {
            test: /\.js|jsx$/,
            use: 'babel-loader',
            exclude: /(node_modules|bower_components)/
          },
    
  • 创建.tsx文件

    import  React from "react"
    
    const TsTodoList : React.FC = () => {
      return (
        <div>我是TS版本的tosolist</div>
      )
    }
    
    export default TsTodoList
    
    
  • 创建.ts文件

    const key: string = '叶俊宽'
    class Animal {
      name: string = '叶俊宽'
      private age: number = 13
    
      getName(): void {
        console.log(this.name)
      }
    
      getInfo(): string {
        return this.name + this.age
      }
    
      setName(name: string): void {
        this.name = name
      }
    
      static getAge(): void {
        console.log(111)
      }
    
    }
    
    class Dog extends Animal{
      constructor() {
        super()
      }
    }
    
    export default Dog
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值