使用 TypeScript
TypeScript 是一种通过添加类型定义来扩展 JavaScript 的语言。新的 React Native 项目默认目标是 TypeScript,但也支持 JavaScript 和 Flow。
TypeScript 入门
通过 React Native CLI 或像 Ignite 这样的流行模板创建的新项目将默认使用 TypeScript。
TypeScript 也可以与 Expo 一起使用,Expo 维护着 TypeScript 模板,或者当您向项目中添加 .ts 或 .tsx 文件时,它会提示您自动安装和配置 TypeScript。
npx create-expo-app --template
为现有项目添加 TypeScript
- 将 TypeScript、类型和 ESLint 插件添加到您的项目中。
- npm
- Yarn
npm install -D typescript @react-native/typescript-config @types/jest @types/react @types/react-test-renderer
yarn add --dev typescript @react-native/typescript-config @types/jest @types/react @types/react-test-renderer
此命令会添加所有依赖项的最新版本。您可能需要更改版本以匹配您的项目使用的现有包。您可以使用 React Native Upgrade Helper 等工具来查看 React Native 随附的版本。
- 添加 TypeScript 配置文件。在项目根目录下创建一个
tsconfig.json文件。
{
"extends": "@react-native/typescript-config"
}
- 将 JavaScript 文件重命名为
*.tsx。
您应该保持 ./index.js 入口文件不变,否则在打包生产版本时可能会遇到问题。
- 运行
tsc来为您的新 TypeScript 文件进行类型检查。
- npm
- Yarn
npx tsc
yarn tsc
使用 JavaScript 而不是 TypeScript
React Native 默认将新应用程序设置为 TypeScript,但仍可使用 JavaScript。扩展名为 .jsx 的文件将被视为 JavaScript 而不是 TypeScript,并且不会进行类型检查。TypeScript 模块仍然可以导入 JavaScript 模块,反之亦然。
TypeScript 和 React Native 的工作原理
开箱即用,TypeScript 源文件在打包时会由 Babel 进行转换。我们建议您仅将 TypeScript 编译器用于类型检查。这是 tsc 在新创建应用程序中的默认行为。如果您有现有 TypeScript 代码要移植到 React Native,那么使用 Babel 而不是 TypeScript 会有一些注意事项。
React Native + TypeScript 的样子
您可以通过 React.Component<Props, State> 为 React 组件的 Props 和 State 提供接口,这将在 JSX 中使用该组件时提供类型检查和编辑器自动补全功能。
import {useState} from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';
export type Props = {
name: string;
baseEnthusiasmLevel?: number;
};
function Hello({name, baseEnthusiasmLevel = 0}: Props) {
const [enthusiasmLevel, setEnthusiasmLevel] = useState(
baseEnthusiasmLevel,
);
const onIncrement = () =>
setEnthusiasmLevel(enthusiasmLevel + 1);
const onDecrement = () =>
setEnthusiasmLevel(
enthusiasmLevel > 0 ? enthusiasmLevel - 1 : 0,
);
const getExclamationMarks = (numChars: number) =>
numChars > 0 ? Array(numChars + 1).join('!') : '';
return (
<View style={styles.container}>
<Text style={styles.greeting}>
Hello {name}
{getExclamationMarks(enthusiasmLevel)}
</Text>
<View>
<Button
title="Increase enthusiasm"
accessibilityLabel="increment"
onPress={onIncrement}
color="blue"
/>
<Button
title="Decrease enthusiasm"
accessibilityLabel="decrement"
onPress={onDecrement}
color="red"
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
greeting: {
fontSize: 20,
fontWeight: 'bold',
margin: 16,
},
});
export default Hello;
您可以在 TypeScript playground 中探索更多语法。
在哪里可以找到有用的建议
- TypeScript Handbook
- React 关于 TypeScript 的文档
- React + TypeScript Cheatsheets 提供了关于如何使用 React 和 TypeScript 的良好概述。
在 TypeScript 中使用自定义路径别名
要使用自定义路径别名与 TypeScript 一起使用,您需要同时为 Babel 和 TypeScript 设置路径别名。方法如下:
- 编辑您的
tsconfig.json文件,以包含您的自定义路径映射。将src根目录下的任何内容设置为无需前导路径引用即可访问,并通过使用tests/File.tsx来允许访问任何测试文件。
{
- "extends": "@react-native/typescript-config"
+ "extends": "@react-native/typescript-config",
+ "compilerOptions": {
+ "baseUrl": ".",
+ "paths": {
+ "*": ["src/*"],
+ "tests": ["tests/*"],
+ "@components/*": ["src/components/*"],
+ },
+ }
}
- 将
babel-plugin-module-resolver添加为项目的开发依赖项。
- npm
- Yarn
npm install --save-dev babel-plugin-module-resolver
yarn add --dev babel-plugin-module-resolver
- 最后,配置您的
babel.config.js(请注意,您的babel.config.js的语法与您的tsconfig.json不同)。
{
presets: ['module:metro-react-native-babel-preset'],
+ plugins: [
+ [
+ 'module-resolver',
+ {
+ root: ['./src'],
+ extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
+ alias: {
+ tests: ['./tests/'],
+ "@components": "./src/components",
+ }
+ }
+ ]
+ ]
}