一懈凹、在RN項(xiàng)目中添加TypeScript
yarn add --dev typescriptyarn add --dev react-native-typescript-transformeryarn tsc --init --pretty --jsx react// 創(chuàng)建tsconfig.json文件linux: touch rn-cli.config.js windows: type nul > rn-cli.config.jsyarn add --dev@types/react@types/react-native
二吐辙、找到剛才創(chuàng)建的tsconfig.json文件,取消下面這行的注釋
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
三蘸劈、打開(kāi)剛才創(chuàng)建的rn-cli.config.js文件,添加以下內(nèi)容
module.exports= {? getTransformModulePath() {returnrequire.resolve('react-native-typescript-transformer');? },? getSourceExts() {return['ts','tsx'];? },};
四尊沸、修改文件名后綴
App.js?修改為?App.tsx
五威沫、按照提示安裝包
如果編輯器安裝了TypeScript的插件贤惯,修改成.tsx后綴的文件將會(huì)報(bào)錯(cuò),鼠標(biāo)移入報(bào)錯(cuò)信息棒掠,將會(huì)有以下提示信息
[ts]無(wú)法找到模塊“react”的聲明文件孵构。“c:/Users/YOURUSER/PATH/TO/YOURPROJECTNAME/node_modules/react/index.js”隱式擁有"any"類(lèi)型烟很。? 嘗試"npm install @types/react"(如果存在)颈墅,或者添加一個(gè)包含“聲明模塊‘react’”的新聲明文件(.d.ts);
執(zhí)行?yarn add --dev @types/jest @types/react @types/react-native @types/react-test-renderer
修改文件引入方式
-importReact, { Component }from'react';+importReactfrom'react'+import{ Component }from'react';
更新
配置好TypeScript后雾袱,使用es6語(yǔ)法時(shí)恤筛,還是會(huì)發(fā)生[ts] 'Promise' only refers to a type, but is being used as a value here.的報(bào)錯(cuò),修改tsconfig.json文件芹橡,找到"target": "es5",修改為es6