使用 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="提升热情"
accessibilityLabel="increment"
onPress={onIncrement}
color="blue"
/>
<Button
title="降低热情"
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 对如何在 TypeScript 中使用 React 有很好的概述
在 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",
+ }
+ }
+ ]
+ ]
}