📅  最后修改于: 2023-12-03 15:22:40.165000             🧑  作者: Mango
在本教程中,我们将学习如何创建一个使用 TypeScript 编写的 React Native 应用程序。我们将使用基于 Expo 的 React Native 框架。
首先,我们需要在本地安装 Expo CLI。我们可以使用以下命令来安装:
npm install -g expo-cli
此命令将全局安装 Expo CLI。如果您已经全局安装过 Expo CLI,则可以跳过此步骤。
我们可以使用 Expo CLI 创建一个新的 React Native 项目。使用以下命令:
expo init my-app
这将创建一个名为 my-app
的新项目。您可以为您的项目选择任何名称。
在安装过程中,您将被要求选择项目类型。我们需要选择 TypeScript 模板。使用键盘方向键选择 minimal (TypeScript)
并按 Enter
。
Expo CLI 将会下载项目的依赖。在下载完成后,我们可以开始与项目一起使用。
要运行项目,请使用以下命令:
cd my-app
npm start
这将启动 Expo DevTools,并在浏览器中打开一个新页面。在页面中,您将看到 QR 码。使用 Expo Go 应用程序扫描此码,即可在您的设备上运行应用程序。
我们需要将 TypeScript 添加到项目中。我们可以使用以下命令:
npm install --save-dev typescript @types/react @types/react-native @types/expo
此命令将安装 TypeScript 和必要的类型声明。我们还需要添加 tsconfig.json
文件,该文件定义了 TypeScript 编译器的设置。
我们可以手动创建 tsconfig.json
文件,也可以使用 TypeScript CLI 创建。使用以下命令来运行 TypeScript CLI 并创建 tsconfig.json
:
npx tsc --init
这将创建一个基本的 tsconfig.json
文件。我们需要更新文件并添加以下配置:
"jsx": "react",
"moduleResolution": "node",
"noEmit": true,
"allowJs": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"lib": [
"es6",
"dom",
"esnext.asynciterable"
],
"plugins": [{
"name": "typescript-tslint-plugin"
}]
此 tsconfig.json
文件包含了必需的配置项,以使 TypeScript 在 React Native 中运行良好。
我们还需要更新 App.tsx
文件。我们可以改为使用 TypeScript 来编写此文件,因此我们需要更改文件扩展名为 .tsx
。
注意以下行:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
我们需要将文件中的 JS 导入语句更改为 TypeScript 格式:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text>Hello world!</Text>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
在这个版本中,我们已经将 React Native 项目转换为了 React Native TypeScript 项目。现在,我们可以使用 TypeScript 在 React Native 中进行开发。