creat-react-app
引入typescript
-
安装
typescript
相关开发依赖npm install --save @types/react @types/react-dom
使用@types/前缀表示我们要额外获取
react
和react-dom
的声明文件,可以像品势引入一样,不安装这两个依赖,导入方式是这个样子的impore * as React from 'react' import * as ReactDOM from 'react-dom'
-
安装开发依赖
npm install typescript awesome-typescript-loader source-map-loader -D
这些依赖可以使得
typescript
和webpack
更好的工作。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