美文网首页
TypeScript In React-Native

TypeScript In React-Native

作者: 我叫傻先生 | 来源:发表于2019-04-19 11:17 被阅读0次
一、在RN项目中添加TypeScript
yarn add --dev typescript
yarn add --dev react-native-typescript-transformer
yarn tsc --init --pretty --jsx react // 创建tsconfig.json文件
linux: touch rn-cli.config.js 
windows: type nul > rn-cli.config.js
yarn add --dev @types/react @types/react-native
二、找到刚才创建的tsconfig.json文件,取消下面这行的注释

// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */

三、打开刚才创建的rn-cli.config.js文件,添加以下内容
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);

执行 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语法时,还是会发生[ts] 'Promise' only refers to a type, but is being used as a value here.的报错,修改tsconfig.json文件,找到"target": "es5",修改为es6

相关文章

网友评论

      本文标题:TypeScript In React-Native

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