使用 TypeScript
TypeScript 是一种通过添加类型定义来扩展 JavaScript 的语言。新的 React Native 项目默认使用 TypeScript,但也支持 JavaScript 和 Flow。
TypeScript 入门
由 React Native CLI 或流行模板(如 Ignite)创建的新项目默认会使用 TypeScript。
TypeScript 也可与 Expo 一起使用,它维护着 TypeScript 模板,或者当你的项目中添加了 .ts 或 .tsx 文件时,会提示你自动安装和配置 TypeScript。
npx create-expo-app --template
向现有项目添加 TypeScript
- 将 TypeScript、类型定义和 ESLint 插件添加到你的项目中。
- npm
- Yarn
npm install -D @tsconfig/react-native @types/jest @types/react @types/react-test-renderer typescript
yarn add --dev @tsconfig/react-native @types/jest @types/react @types/react-test-renderer typescript
此命令添加每个依赖项的最新版本。版本可能需要更改以匹配项目现有的包。你可以使用像 React Native Upgrade Helper 这样的工具来查看 React Native 发布的版本。
- 添加 TypeScript 配置文件。在项目根目录创建一个
tsconfig.json:
{
"extends": "@tsconfig/react-native/tsconfig.json"
}
- 将 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 默认行为。如果你有需要移植到 React Native 的现有 TypeScript 代码,使用 Babel 而不是 TypeScript 有 一两个注意事项。
React Native + TypeScript 是什么样子的
你可以通过 React.Component<Props, State> 为 React 组件的 Props 和 State 提供接口,这将在 JSX 中使用该组件时提供类型检查和编辑器自动补全。
import React from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';
export type Props = {
name: string;
baseEnthusiasmLevel?: number;
};
const Hello: React.FC<Props> = ({
name,
baseEnthusiasmLevel = 0,
}) => {
const [enthusiasmLevel, setEnthusiasmLevel] = React.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": "@tsconfig/react-native/tsconfig.json"
+ "extends": "@tsconfig/react-native/tsconfig.json",
+ "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",
+ }
+ }
+ ]
+ ]
}