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











网友评论