美文网首页
creat-react-app引入typescript

creat-react-app引入typescript

作者: 七七的眼睛 | 来源:发表于2020-01-02 19:40 被阅读0次

    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
      

    相关文章

      网友评论

          本文标题:creat-react-app引入typescript

          本文链接:https://www.haomeiwen.com/subject/tsoooctx.html