一、在RN項目中添加TypeScript
yarn add --dev typescript
yarn add --dev react-native-typescript-transformer
yarn tsc --init --pretty --jsx react // 創(chuàng)建tsconfig.json文件
linux: touch rn-cli.config.js
windows: type nul > rn-cli.config.js
yarn 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. */
三、打開剛才創(chuàng)建的rn-cli.config.js
文件良姆,添加以下內(nèi)容
module.exports = {
getTransformModulePath() {
return require.resolve('react-native-typescript-transformer');
},
getSourceExts() {
return ['ts', 'tsx'];
},
};
四肠虽、修改文件名后綴
App.js
修改為 App.tsx
五、按照提示安裝包
- 如果編輯器安裝了
TypeScript
的插件玛追,修改成.tsx
后綴的文件將會報錯税课,鼠標移入報錯信息闲延,將會有以下提示信息
[ts]
無法找到模塊“react”的聲明文件『妫“c:/Users/YOURUSER/PATH/TO/YOURPROJECTNAME/node_modules/react/index.js”隱式擁有 "any" 類型垒玲。
嘗試 "npm install @types/react" (如果存在),或者添加一個包含“聲明模塊‘react’”的新聲明文件(.d.ts)啸如;
執(zhí)行 yarn add --dev @types/jest @types/react @types/react-native @types/react-test-renderer
- 修改文件引入方式
-import React, { Component } from 'react';
+import React from 'react'
+import { Component } from 'react';
更新
- 配置好
TypeScript
后侍匙,使用es6
語法時,還是會發(fā)生[ts] 'Promise' only refers to a type, but is being used as a value here.
的報錯叮雳,修改tsconfig.json
文件想暗,找到"target": "es5",
修改為es6