将 TypeScript 与 React Native 结合使用
JavaScript!我们都喜欢它。但我们中的一些人也喜欢类型。幸运的是,存在向 JavaScript 添加更强类型的方法。我最喜欢的是 TypeScript,但 React Native 开箱即用地支持 Flow。您更喜欢哪个取决于个人喜好,它们各自有自己的方法来为 JavaScript 添加类型的魔力。今天,我们将看看如何在 React Native 应用程序中使用 TypeScript。
这篇文章使用 Microsoft 的 TypeScript-React-Native-Starter 仓库作为指南。
更新:自从撰写这篇博客文章以来,事情变得更加容易。您可以通过运行一个命令来替换此博客文章中描述的所有设置
npx react-native init MyAwesomeProject --template react-native-template-typescript
然而,Babel 的 TypeScript 支持确实存在一些限制,上面的博客文章详细介绍了这些限制。这篇文章中概述的步骤仍然有效,Artsy 仍然在生产环境中使用 react-native-typescript-transformer,但使用 React Native 和 TypeScript 最快入门的方法是使用上面的命令。如果需要,您可以随时稍后切换。
无论如何,玩得开心!原始博客文章继续如下。
先决条件
因为您可能在几种不同的平台上进行开发,针对几种不同类型的设备,所以基本设置可能很复杂。您应该首先确保您可以运行没有 TypeScript 的普通 React Native 应用程序。按照 React Native 网站上的说明开始。当您成功部署到设备或模拟器后,您就可以开始 TypeScript React Native 应用程序了。
初始化
一旦您尝试搭建一个普通的 React Native 项目,您就可以开始添加 TypeScript 了。让我们继续这样做。
react-native init MyAwesomeProject
cd MyAwesomeProject
添加 TypeScript
下一步是将 TypeScript 添加到您的项目中。以下命令将
- 将 TypeScript 添加到您的项目
- 将 React Native TypeScript Transformer 添加到您的项目
- 初始化一个空的 TypeScript 配置文件,我们将在下一步配置它
- 添加一个空的 React Native TypeScript Transformer 配置文件,我们将在下一步配置它
- 为 React 和 React Native 添加 类型定义
好的,让我们继续运行这些。
yarn add --dev typescript
yarn add --dev react-native-typescript-transformer
yarn tsc --init --pretty --jsx react
touch rn-cli.config.js
yarn add --dev @types/react @types/react-native
tsconfig.json
文件包含 TypeScript 编译器的所有设置。上面命令创建的默认值大部分都很好,但打开文件并取消注释以下行
{
/* Search the config file for the following line and uncomment it. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
}
rn-cli.config.js
文件包含 React Native TypeScript Transformer 的设置。打开它并添加以下内容
module.exports = {
getTransformModulePath() {
return require.resolve('react-native-typescript-transformer');
},
getSourceExts() {
return ['ts', 'tsx'];
},
};
迁移到 TypeScript
将生成的 App.js
和 __tests_/App.js
文件重命名为 App.tsx
。index.js
需要使用 .js
扩展名。所有新文件都应使用 .tsx
扩展名(如果文件不包含任何 JSX,则使用 .ts
)。
如果您现在尝试运行该应用程序,则会收到类似 object prototype may only be an object or null
的错误。这是由于无法从 React 导入默认导出以及同一行上的命名导出引起的。打开 App.tsx
并修改文件顶部的导入
-import React, { Component } from 'react';
+import React from 'react'
+import { Component } from 'react';
其中一些与 Babel 和 TypeScript 如何与 CommonJS 模块互操作的差异有关。将来,两者将在相同的行为上稳定下来。
此时,您应该能够运行 React Native 应用程序。
添加 TypeScript 测试基础设施
React Native 附带了 Jest,因此为了使用 TypeScript 测试 React Native 应用程序,我们将需要将 ts-jest 添加到我们的 devDependencies
中。
yarn add --dev ts-jest
然后,我们将打开我们的 package.json
并将 jest
字段替换为以下内容
{
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transform": {
"^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
"\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
"\\.snap$",
"<rootDir>/node_modules/"
],
"cacheDirectory": ".jest/cache"
}
}
这将配置 Jest 以使用 ts-jest
运行 .ts
和 .tsx
文件。
安装依赖类型声明
为了在 TypeScript 中获得最佳体验,我们希望类型检查器了解我们依赖项的形状和 API。某些库将发布带有 .d.ts
文件(类型声明/类型定义文件)的包,这些文件可以描述底层 JavaScript 的形状。对于其他库,我们将需要显式安装 @types/
npm 范围内的相应包。
例如,在这里我们将需要 Jest、React 和 React Native 以及 React Test Renderer 的类型。
yarn add --dev @types/jest @types/react @types/react-native @types/react-test-renderer
我们将这些声明文件包保存到我们的开发依赖项中,因为这是一个 React Native 应用程序,仅在开发期间而不是在运行时使用这些依赖项。如果我们要将库发布到 NPM,我们可能必须将其中一些类型依赖项添加为常规依赖项。
您可以在此处阅读有关获取 .d.ts
文件的更多信息。
忽略更多文件
对于您的源代码控制,您将需要开始忽略 .jest
文件夹。如果您正在使用 git,我们可以只向我们的 .gitignore
文件添加条目。
# Jest
#
.jest/
作为检查点,请考虑将您的文件提交到版本控制。
git init
git add .gitignore # import to do this first, to ignore our files
git add .
git commit -am "Initial commit."
添加组件
让我们向我们的应用程序添加一个组件。让我们继续创建一个 Hello.tsx
组件。这是一个教学组件,不是您实际上会在应用程序中编写的东西,而是一些非平凡的东西,展示如何在 React Native 中使用 TypeScript。
创建一个 components
目录并添加以下示例。
// components/Hello.tsx
import React from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';
export interface Props {
name: string;
enthusiasmLevel?: number;
}
interface State {
enthusiasmLevel: number;
}
export class Hello extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
if ((props.enthusiasmLevel || 0) <= 0) {
throw new Error(
'You could be a little more enthusiastic. :D',
);
}
this.state = {
enthusiasmLevel: props.enthusiasmLevel || 1,
};
}
onIncrement = () =>
this.setState({
enthusiasmLevel: this.state.enthusiasmLevel + 1,
});
onDecrement = () =>
this.setState({
enthusiasmLevel: this.state.enthusiasmLevel - 1,
});
getExclamationMarks = (numChars: number) =>
Array(numChars + 1).join('!');
render() {
return (
<View style={styles.root}>
<Text style={styles.greeting}>
Hello{' '}
{this.props.name +
this.getExclamationMarks(this.state.enthusiasmLevel)}
</Text>
<View style={styles.buttons}>
<View style={styles.button}>
<Button
title="-"
onPress={this.onDecrement}
accessibilityLabel="decrement"
color="red"
/>
</View>
<View style={styles.button}>
<Button
title="+"
onPress={this.onIncrement}
accessibilityLabel="increment"
color="blue"
/>
</View>
</View>
</View>
);
}
}
// styles
const styles = StyleSheet.create({
root: {
alignItems: 'center',
alignSelf: 'center',
},
buttons: {
flexDirection: 'row',
minHeight: 70,
alignItems: 'stretch',
alignSelf: 'center',
borderWidth: 5,
},
button: {
flex: 1,
paddingVertical: 0,
},
greeting: {
color: '#999',
fontWeight: 'bold',
},
});
哇!内容很多,但让我们分解一下
- 我们没有渲染像
div
、span
、h1
等 HTML 元素,而是渲染像View
和Button
这样的组件。这些是跨不同平台的原生组件。 - 样式是使用 React Native 提供的
StyleSheet.create
函数指定的。React 的样式表允许我们使用 Flexbox 控制布局,并使用类似于 CSS 中的其他结构进行样式设置。
添加组件测试
现在我们有了一个组件,让我们尝试测试它。
我们已经安装了 Jest 作为测试运行器。我们将为我们的组件编写快照测试,让我们添加快照测试所需的附加组件
yarn add --dev react-addons-test-utils
现在让我们在 components
目录中创建一个 __tests__
文件夹,并为 Hello.tsx
添加一个测试
// components/__tests__/Hello.tsx
import React from 'react';
import renderer from 'react-test-renderer';
import {Hello} from '../Hello';
it('renders correctly with defaults', () => {
const button = renderer
.create(<Hello name="World" enthusiasmLevel={1} />)
.toJSON();
expect(button).toMatchSnapshot();
});
首次运行测试时,它将创建渲染组件的快照,并将其存储在 components/__tests__/__snapshots__/Hello.tsx.snap
文件中。当您修改组件时,您需要更新快照并查看更新是否有意外更改。您可以在此处阅读有关测试 React Native 组件的更多信息。
下一步
查看官方 React 教程和状态管理库 Redux。这些资源在编写 React Native 应用程序时可能会有所帮助。此外,您可能需要查看 ReactXP,这是一个完全用 TypeScript 编写的组件库,它同时支持 Web 上的 React 和 React Native。
在更类型安全的 React Native 开发环境中玩得开心!