⒈初始化 React Native环境
参考https://reactnative.cn/docs/getting-started.html
⒉安装React Native官方的脚手架工具
npm install -g react-native-cli
⒊使用React Native脚手架初始化项目
#默认是JavaScript react-native init ts_react_native #可以直接使用TypeScript初始化 react-native init ts_react_native --template typescript
⒋安装watchman
watchman用于监控React Native项目中文件的变动,经常有开发者忘记安装watchman而导致项目无法启动的情况
cd ts_react_native
y watchman
⒌更改项目为TypeScript环境
1.将TypeScript以及React Native和Jest的类型添加到您的项目中。
yarn add typescript @types/jest @types/react @types/react-native @types/react-test-renderer # or for npm npm install --save-dev @types/jest @types/react @types/react-native @types/react-test-renderer
⒉在项目的根目录中创建TypeScript配置文件tsconfig.json:
{ "compilerOptions": { "allowJs": true, "allowSyntheticDefaultImports": true, "esModuleInterop": true, "isolatedModules": true, "jsx": "react", "lib": ["es6"], "moduleResolution": "node", "noEmit": true, "strict": true, "target": "esnext" }, "exclude": [ "node_modules", "babel.config.js", "metro.config.js", "jest.config.js" ] }
3.创建一个jest.config.js
文件来配置Jest以使用TypeScript
module.exports = { preset: 'react-native', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], };
4.重命名一个JavaScript文件为 *.tsx
5.运行yarn tsc
以检查新的TypeScript文件。
6.启动项目
#启动ios yarn react-native run-ios #启动Android yarn react-native run-android