使用 TypeScript

有关使用 TypeScript 配置 Expo 项目的深入指南。


Expo 对 TypeScript 提供一流的支持。Expo SDK 的 JavaScript 接口是用 TypeScript 编写的。

🌐 Expo has first-class support for TypeScript. The JavaScript interface of Expo SDK is written in TypeScript.

本指南提供了一种快速开始新项目的方法,以及将现有的基于 JavaScript 的 Expo 项目迁移到使用 TypeScript 的步骤。

🌐 This guide provides a quick way to get started for a new project and also steps to migrate your existing JavaScript based Expo project to use TypeScript.

快速开始

🌐 Quick start

要创建新项目,请使用包含基本 TypeScript 配置、示例代码和基本导航结构的默认模板:

🌐 To create a new project, use the default template which includes base TypeScript configuration, example code, and basic navigation structure:

Terminal
npx create-expo-app@latest

使用上述命令创建新项目后,请确保遵循以下说明:

🌐 After you create a new project using the command above, make sure to follow instructions from:

  • 设置你的环境,其中提供了设置本地开发环境所需的步骤。
  • 开始开发,提供有关启动开发服务器、文件结构以及其他功能详细信息的信息。

迁移现有 JavaScript 项目

🌐 Migrating existing JavaScript project

要迁移你现有的基于 JavaScript 的项目以使用 TypeScript,请按照以下说明操作:

🌐 To migrate your existing JavaScript based project to use TypeScript, follow the instructions below:

1

将文件重命名为使用 .tsx 或 .ts 扩展名

🌐 Rename files to use .tsx or .ts extension

重命名文件以将它们转换为 TypeScript。例如,从根组件文件开始,如 App.js,然后将其重命名为 App.tsx

🌐 Rename files to convert them to TypeScript. For example, start with the root component file such as App.js and rename it to App.tsx:

Terminal
mv App.js App.tsx

信息 提示: 如果文件包含 React 组件(JSX),请使用 .tsx 扩展名。如果文件不包含任何 JSX,则可以使用 .ts 扩展名。

2

安装所需的开发依赖

🌐 Install required development dependencies

要在 package.json 中安装所需的 devDependencies,例如 typescript@types/react

🌐 To install required devDependencies such as typescript and @types/react in package.json:

Terminal
npx expo install typescript @types/react --dev
Terminal
npx expo install typescript @types/react "--" --dev

信息 另外,可以运行 npx expo start 命令来安装 typescript@types/react 开发依赖。

使用 tsc进行项目文件类型检查

要对项目文件进行类型检查,请在项目目录的根目录下运行 tsc 命令:

🌐 To type check your project's files run tsc command within the root of your project directory:

Terminal
# For npm
npm run tsc

# For yarn
yarn tsc

3

使用 tsconfig.json 添加基础配置

🌐 Add base configuration with tsconfig.json

一个项目的 tsconfig.json 默认应该扩展 expo/tsconfig.base。你可以通过运行以下命令自动生成一个 tsconfig.json 文件:

🌐 A project's tsconfig.json should extend expo/tsconfig.base by default. You can automatically generate a tsconfig.json file by running the command:

Terminal
npx expo customize tsconfig.json

tsconfig.json 中的默认配置对用户友好,并鼓励采用。如果你希望 严格类型检查 并减少运行时错误的可能性,请在 compilerOptions 下启用 strict

🌐 The default configuration in tsconfig.json is user-friendly and encourages adoption. If you prefer strict type checking and reduce the chances of runtime errors, enable strict under compilerOptions:

tsconfig.json
{ "extends": "expo/tsconfig.base", "compilerOptions": { "strict": true } }

4

路径别名(可选)

🌐 Path aliases (Optional)

Expo CLI 会自动支持 tsconfig.json 中的 路径别名。它允许使用自定义别名来导入模块,而不是使用相对路径。

🌐 Expo CLI supports path aliases in tsconfig.json automatically. It allows importing modules with custom aliases instead of relative paths.

例如,要使用别名 @/components/Buttonsrc/components/Button.tsx 导入 Button 组件,在 tsconfig.json 中添加别名 @/* 并将其设置为 src 目录:

🌐 For example, to import Button component from src/components/Button.tsx using the alias @/components/Button, add the alias @/* in tsconfig.json and set it to the src directory:

tsconfig.json
{ "extends": "expo/tsconfig.base", "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] } } }
禁用路径别名

tsconfigPaths 默认是启用的,这允许你设置路径别名。你可以通过在项目的 应用配置 中将 tsconfigPaths 设置为 false 来禁用它:

app.json
{ "expo": { "experiments": { "tsconfigPaths": false } } }

注意事项

🌐 Considerations

使用路径别名时,请考虑以下内容:

🌐 When using path aliases, consider the following:

  • 修改 tsconfig.json 后,请重启 Expo CLI 以更新路径别名。别名更改时无需清除 Metro 缓存。
  • 如果不使用 TypeScript,jsconfig.json 可以作为 tsconfig.json 的替代方案。
  • 定义路径别名会增加额外的解析时间。
  • 路径别名仅受 Metro(包括 Metro web)支持,而不支持已弃用的 @expo/webpack-config
  • 裸项目需要为此功能进行额外设置。更多信息请参阅Metro 设置指南

5

绝对导入(可选)

🌐 Absolute imports (Optional)

要从项目根目录启用绝对导入,请在 tsconfig.json 文件中定义 compilerOptions.baseUrl

🌐 To enable absolute imports from a project's root directory, define compilerOptions.baseUrl the tsconfig.json file:

tsconfig.json
{ "extends": "expo/tsconfig.base", "compilerOptions": { "baseUrl": "./" } }

例如,设置上述配置后,可以从路径 src/components/Button 导入 Button 组件:

🌐 For example, setting the above configuration allows importing Button component from the path src/components/Button:

import Button from 'src/components/Button';

注意事项

🌐 Considerations

使用绝对导入时,请考虑以下内容:

🌐 When using absolute imports, consider the following:

  • compilerOptions.paths 是相对于 compilerOptions.baseUrl 解析的(如果定义了 compilerOptions.baseUrl),否则它们是相对于项目根目录解析的。
  • compilerOptions.baseUrl 会在 node 模块之前被解析。这意味着如果你有一个名为 ./path.ts 的文件,它可以被导入,而不是名为 path 的 node 模块。
  • 在修改 tsconfig.json 后,重新启动 Expo CLI 是更新 compilerOptions.baseUrl 所必需的。
  • 如果你不使用 TypeScript,jsconfig.json 可以作为 tsconfig.json 的替代方案。
  • 绝对导入仅由 Metro(包括 Metro web)支持,而 @expo/webpack-config 不支持。
  • 裸项目需要为此功能进行额外的设置。请参阅 版本化 Metro 设置指南 了解更多信息。

类型生成

🌐 Type generation

一些 Expo 库同时提供静态类型和类型生成能力。这些类型会在项目构建时或运行 npx expo customize tsconfig.json 命令时自动生成。

🌐 Some Expo libraries provide both static types and type generation capabilities. These types are automatically generated when the project builds or by running the npx expo customize tsconfig.json command.

用于项目配置文件的 TypeScript

🌐 TypeScript for project's config files

要在配置文件(例如 metro.config.jsapp.config.js)中使用 TypeScript,需要进行额外的设置。

🌐 Additional setup is required to use TypeScript for configuration files such as metro.config.js or app.config.js.

tsx 安装为开发依赖,并使用其 tsx/cjs require 钩子 在 JS 配置文件中导入 TypeScript 文件。该钩子允许使用 TypeScript 导入,同时保持根文件为 JavaScript。下面的命令添加了 tsx,以便 import 'tsx/cjs' 在接下来的子部分示例中工作。

🌐 Install tsx as a dev dependency and utilize its tsx/cjs require hook to import TypeScript files within your JS configuration file. This hook allows TypeScript imports while keeping the root file as JavaScript. The command below adds tsx so import 'tsx/cjs' works in the following sub-section examples.

Terminal
npx expo install tsx --dev
Terminal
npx expo install tsx "--" --dev

metro.config.js

更新 metro.config.js 以导入 metro.config.ts 文件:

🌐 Update metro.config.js to require metro.config.ts file:

metro.config.js
require('tsx/cjs'); // Add this to import TypeScript files module.exports = require('./metro.config.ts');

使用你的项目的 Metro 配置更新 metro.config.ts 文件:

🌐 Update metro.config.ts file with your project's metro configuration:

metro.config.ts
import { getDefaultConfig } from 'expo/metro-config'; const config = getDefaultConfig(__dirname); module.exports = config;
已弃用:webpack.config.js

安装 @expo/webpack-config 软件包。

🌐 Install the @expo/webpack-config package.

webpack.config.js
require('tsx/cjs'); // Add this to import TypeScript files module.exports = require('./webpack.config.ts');
webpack.config.ts
import createExpoWebpackConfigAsync from '@expo/webpack-config/webpack'; import { Arguments, Environment } from '@expo/webpack-config/webpack/types'; module.exports = async function (env: Environment, argv: Arguments) { const config = await createExpoWebpackConfigAsync(env, argv); // Customize the config before returning it. return config; };

app.config.js

app.config.ts 默认受支持。但它不支持外部 TypeScript 模块或 tsconfig.json 自定义。你可以使用以下方法获取更全面的 TypeScript 配置:

app.config.ts
import 'tsx/cjs'; // Add this to import TypeScript files import { ExpoConfig } from 'expo/config'; const config: ExpoConfig = { name: 'my-app', slug: 'my-app', }; export default config;

其他 TypeScript 功能

🌐 Other TypeScript features

某些语言特性可能需要额外的配置。例如,如果你想使用装饰器,你需要添加 experimentalDecorators 选项。有关可用属性的更多信息,请参阅 TypeScript 编译器选项 文档。

🌐 Some language features may require additional configuration. For example, if you want to use decorators you'll need to add the experimentalDecorators option. For more information on the available properties see the TypeScript compiler options documentation.

了解如何使用 TypeScript

🌐 Learn how to use TypeScript

学习 TypeScript 的一个好起点是官方的 TypeScript 手册

🌐 A good place to start learning TypeScript is the official TypeScript Handbook.

对于 TypeScript 和 React 组件, 我们建议参考 React TypeScript CheatSheet 来学习如何在各种常见情况下为你的 React 组件添加类型。