React Native 项目集成 Typescript

React Native项目搭建(react-native + typescript)

1、安装react-nativecli工具

npm i -g react-native-cli

或者

yarn add global react-native-cli

2、创建react-native项目

react-native init MyRnProject

项目名称不允许有中划线,如:my-rn-project

3、添加Typescript

  • 安装typescript包

    yarn add --dev typescript

  • 安装 react-native-typescript-transformer

    yarn add --dev react-native-typescript-transformer

  • 初始化创建tsconfig.json

    yarn tsc --init --pretty --jsx react

  • 创建Native TypeScript Transformer的配置文件

    touch rn-cli.config.js

  • 添加React和React Native的类型包

    yarn add --dev @types/react @types/react-native

注释tsconfig.json中的以下一行:

{
  ...
  // "allowSyntheticDefaultImports": true,
  ...
}

rn-cli.config.js中添加以下内容:

module.exports = {
  getTransformModulePath() {
    return require.resolve("react-native-typescript-transformer");
  },
  getSourceExts() {
    return ["ts", "tsx"];
  }
};

4、集成ts-jest测试

添加 ts-jest依赖

yarn add --dev ts-jest

替换package.json中的jest字段为以下内容:

"jest": {
  "preset": "react-native",
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js"
  ],
  "transform": {
    "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
    "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
  },
  "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
  "testPathIgnorePatterns": [
    "\\.snap$",
    "<rootDir>/node_modules/"
  ],
  "cacheDirectory": ".jest/cache"
}

安装类型声明包

yarn add --dev @types/jest @types/react @types/react-native @types/react-test-renderer

忽略.jest 文件夹

# Jest
#
.jest/

至此React Native + TypeScript 项目就搭建完成了

    原文作者:range
    原文地址: https://segmentfault.com/a/1190000017559320
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞