首页指南参考教程

使用 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:

  • 设置你的环境 提供设置本地开发环境所需的步骤。

    ¥Set up your environment which provides required steps for setting local development environment.

  • 开始开发 提供有关触发开发服务器、文件结构和其他功能的详细信息。

    ¥Start developing which provides information on triggering a development server, file structure, and details about other features.

迁移现有 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
# For all other package managers
npx expo install -- --save-dev typescript @types/react

# For yarn
yarn add -D typescript @types/react
或者,运行 npx expo start 命令来安装 typescript@types/react dev 依赖。
Type checking project files with 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 the 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
{
  "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/Button 从 src/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
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}
Required configuration to enable path aliases for SDK 49

tsconfigPaths 设置为 true 以在项目的 应用配置 中启用路径别名:

¥Set tsconfigPaths to true to enable path aliases in the project's app config:

app.json
{
  "expo": {
    "experiments": {
      "tsconfigPaths": true
    }
  }
}
Disable path aliases for SDK 50 and above

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

¥tsconfigPaths is enabled by default which allows you to set path aliases. You can disable it by setting tsconfigPaths to false in the project's app config:

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

注意事项

¥Considerations

使用路径别名时,请考虑以下事项:

¥When using path aliases, consider the following:

  • 修改 tsconfig.json 以更新路径别名后重新启动 Expo CLI。当别名更改时,你不需要清除 Metro 缓存。

    ¥Restart Expo CLI after modifying tsconfig.json to update path aliases. You don't need to clear the Metro cache when the aliases change.

  • 如果不使用 TypeScript,jsconfig.json 可以作为 tsconfig.json 的替代品。

    ¥If not using TypeScript, jsconfig.json can serve as an alternative to tsconfig.json.

  • 路径别名在定义时会增加额外的解析时间。

    ¥Path aliases add additional resolution time when defined.

  • 路径别名仅受 Metro(包括 Metro web)支持,而不受已弃用的 @expo/webpack-config 支持。

    ¥Path aliases are only supported by Metro (including Metro web) and not by the deprecated @expo/webpack-config.

  • 裸项目需要对此功能进行额外设置。请参阅 Metro 设置指南 了解更多信息。

    ¥Bare projects require additional setup for this feature. See the Metro setup guide for more information.

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
{
  "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';
Required configuration to enable absolute imports for SDK 49

tsconfigPaths 设置为 true,以在项目的 应用配置 中启用绝对导入:

¥Set tsconfigPaths to true to enable absolute imports in the project's app config:

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

注意事项

¥Considerations

使用绝对导入时,请考虑以下事项:

¥When using absolute imports, consider the following:

  • 如果定义了 compilerOptions.paths,则相对于 compilerOptions.baseUrl 进行解析,否则根据项目根目录进行解析。

    ¥compilerOptions.paths are resolved relative to the compilerOptions.baseUrl if it is defined, otherwise they're resolved against the project root directory.

  • compilerOptions.baseUrl 在节点模块之前被解析。这意味着如果你有一个名为 ./path.ts 的文件,则可以导入它而不是名为 path 的节点模块。

    ¥compilerOptions.baseUrl is resolved before node modules. This means if you have a file named ./path.ts, it can be imported instead of a node module named path.

  • 修改 tsconfig.json 后需要重新启动 Expo CLI 才能更新 compilerOptions.baseUrl

    ¥Restarting Expo CLI is necessary to update compilerOptions.baseUrl after modifying the tsconfig.json.

  • 如果你不使用 TypeScript,则 jsconfig.json 可以作为 tsconfig.json 的替代方案。

    ¥If you're not using TypeScript, jsconfig.json can serve as an alternative to tsconfig.json.

  • 仅 Metro(包括 Metro web)支持绝对导入,@expo/webpack-config 不支持。

    ¥Absolute imports are only supported by Metro (including Metro web) and not by @expo/webpack-config.

  • 裸项目需要对此功能进行额外设置。请参阅 版本化 Metro 设置指南 了解更多信息。

    ¥Bare projects require additional setup for this feature. See the versioned Metro setup guide for more information.

类型生成

¥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

需要进行其他设置才能使用 TypeScript 配置文件,例如 metro.config.js 或 app.config.js。你需要利用 ts-node 需要钩子 在你的 JS 配置文件中导入 TypeScript 文件。此钩子允许 TypeScript 导入,同时将根文件保留为 JavaScript。

¥Additional setup is required to use TypeScript for configuration files such as metro.config.js or app.config.js. You need to utilize ts-node require hook to import TypeScript files within your JS config file. This hook allows TypeScript imports while keeping the root file as JavaScript.

Terminal
# For all other package managers
npx expo install -- --save-dev ts-node

# For yarn
yarn add -D ts-node

metro.config.js

更新 metro.config.js 以要求 metro.config.ts 文件:

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

metro.config.js
require('ts-node/register');
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;
Deprecated: webpack.config.js

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

¥Install the @expo/webpack-config package.

webpack.config.js
require('ts-node/register');
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 is supported by default. However, it doesn't support external TypeScript modules, or tsconfig.json customization. You can use the following approach to get a more comprehensive TypeScript setup:

app.config.ts
import 'ts-node/register'; // 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 备忘单 来了解如何在各种常见情况下键入 React 组件。

¥For TypeScript and React components, we recommend referring to the React TypeScript CheatSheet to learn how to type your React components in a variety of common situations.

Expo 中文网 - 粤ICP备13048890号