有关使用 TypeScript 配置 Expo 项目的深入指南。
Expo 对 TypeScript 有一流的支持。Expo SDK 的 JavaScript 接口完全用 TypeScript 编写。
¥Expo has first-class support for TypeScript. The JavaScript interface of the Expo SDK is completely written in TypeScript.
请参阅 GitHub 上的示例项目。
¥Get started
¥Quick start with a template
最简单的开始方法是使用 TypeScript 模板初始化新项目:
¥The easiest way to get started is to initialize your new project using a TypeScript template:
-
npx create-expo-app -t expo-template-blank-typescript
对于 npm,请将以下 script
添加到 package.json:
¥For npm, add the following script
to the package.json:
{
"scripts": {
"ts:check": "tsc"
%%placeholder-start%%... %%placeholder-end%%
}
}
然后,要对项目进行类型检查,请运行以下命令:
¥Then, to type-check the project, run the following command:
-
npm run ts:check
-
yarn tsc
当你在项目中创建新的源文件时,如果文件包含 React 组件,则应使用 .ts 扩展名或 .tsx。
¥When you create new source files in your project you should use the .ts extension or the .tsx if the file includes React components.
¥In an existing project
重命名文件以将其转换为 TypeScript。例如,将 App.js 重命名为 App.tsx。如果文件包含 React 组件 (JSX),请使用 .tsx 扩展名。如果文件不包含任何 JSX,你可以使用 .ts 文件扩展名。
¥Rename files to convert them to TypeScript. For example, rename App.js to App.tsx. Use the .tsx extension if the file includes React components (JSX). If the file does not include any JSX, you can use the .ts file extension.
-
mv App.js App.tsx
对于 SDK 48 及更高版本,运行
npx expo start
会提示你安装所需的依赖,例如typescript
和@types/react
。¥For SDK 48 and higher, running
npx expo start
prompts you to install the required dependencies, such astypescript
and@types/react
.
对于 npm,请将以下 script
添加到 package.json:
¥For npm, add the following script
to the package.json:
{
"scripts": {
"ts:check": "tsc"
%%placeholder-start%%... %%placeholder-end%%
}
}
你现在可以运行 npm run ts:check
或 yarn tsc
对项目进行类型检查。
¥You can now run npm run ts:check
or yarn tsc
to type-check the project.
¥Base configuration
你可以使用环境变量
EXPO_NO_TYPESCRIPT_SETUP=1
在 Expo CLI 中禁用 TypeScript 设置¥You can disable the TypeScript setup in Expo CLI with the environment variable
EXPO_NO_TYPESCRIPT_SETUP=1
默认情况下,项目的 tsconfig.json 应扩展 expo/tsconfig.base
。这将设置以下默认 编译器选项(可以在项目的 tsconfig.json 中覆盖):
¥A project's tsconfig.json should extend the expo/tsconfig.base
by default. This sets the following default compiler options (which can be overwritten in your project's tsconfig.json):
你可以通过运行以下命令自动生成 tsconfig.json 文件:
¥You can automatically generate a tsconfig.json file by running the command:
-
npx expo customize tsconfig.json
¥Project configuration
Expo CLI 会自动将你的 tsconfig.json 修改为首选默认值,该默认值针对通用 React 开发进行了优化:
¥Expo CLI will automatically modify your tsconfig.json to the preferred default which is optimized for universal React development:
{
"extends": "expo/tsconfig.base",
"compilerOptions": {},
"include": ["**/*.ts", "**/*.tsx", ".expo/types/**/*.ts", "expo-env.d.ts"]
}
TypeScript 的默认配置是用户友好的并且鼓励采用。但是,如果你更喜欢严格的类型检查,可以通过将 "strict": true
添加到 compilerOptions
来启用它。我们建议启用此功能以最大程度地减少引入运行时错误的机会。
¥The default configuration for TypeScript is user-friendly and encourages adoption. However, if you prefer strict type checking, you can enable it by adding "strict": true
to the compilerOptions
. We recommend enabling this to minimize the chance of introducing runtime errors.
某些语言功能可能需要额外的配置。例如,如果想使用装饰器,你需要添加 experimentalDecorators
选项。有关可用属性的更多信息,请参阅 TypeScript 编译器选项 文档。
¥Some language features may require additional configuration. For example, if 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.
¥Path aliases
Expo CLI 自动支持项目的 tsconfig.json 中的 路径别名。这使你能够使用自定义别名而不是相对路径导入模块。
¥Expo CLI supports path aliases in your project's tsconfig.json automatically. This enables you to import modules using a custom alias instead of a relative path.
例如,如果你在 src/components/Button.tsx 中有一个文件,并希望使用别名 @/components/Button 导入它,如下所示:
¥For example, if you have a file at src/components/Button.tsx and wish to import it using the alias @/components/Button as follows:
import Button from '@/components/Button';
然后只需在项目的 tsconfig.json 中添加别名 @/* 并将其设置到 src 目录即可:
¥Then simply add the alias @/* in the project's tsconfig.json and set it to the src directory:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
使用路径别名时请考虑以下事项:
¥Consider the following when using path aliases:
更改 tsconfig.json 以更新路径别名后重新启动 Expo CLI。当别名更改时,你不需要清除 Metro 缓存。
¥Restart Expo CLI after changing 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
package.
裸项目需要对此功能进行额外设置。请参阅 版本化 Metro 设置指南 了解更多信息。
¥Bare projects require additional setup for this feature. See the versioned Metro setup guide for more information.
默认情况下启用 tsconfigPaths
。你可以通过在项目的 应用配置 中将 tsconfigPaths
设置为 false
来禁用它:
¥tsconfigPaths
is enabled by default. You can disable it by setting tsconfigPaths
to false
in the project's app config:
{
"expo": {
"experiments": {
"tsconfigPaths": false
}
}
}
将 tsconfigPaths
设置为 true
以在项目的 应用配置 中启用路径别名:
¥Set tsconfigPaths
to true
to enable path aliases in the project's app config:
{
"expo": {
"experiments": {
"tsconfigPaths": true
}
}
}
¥Absolute imports
在 SDK 49 及更高版本中可用。
¥Available in SDK 49 and higher.
在 SDK 49 项目中,你需要在项目的 应用配置 中启用绝对导入:
¥In SDK 49 projects, you'll need to enable absolute imports in the project's app config:
{
"expo": {
"experiments": {
"tsconfigPaths": true
}
}
}
当在项目的 tsconfig.json 或 jsconfig.json 文件中定义 compilerOptions.baseUrl
时,将启用从项目根目录的绝对导入。例如:
¥Absolute imports from the project root directory are enabled when compilerOptions.baseUrl
is defined in the project's tsconfig.json or jsconfig.json file. For example:
{
"compilerOptions": {
"baseUrl": "./"
}
}
将启用以下导入:
¥Will enable the following import:
import Button from 'src/components/Button';
// Imports `<compilerOptions.baseUrl>/src/components/Button`
使用绝对导入时请考虑以下事项:
¥Consider the following when using absolute imports:
如果定义了 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.js
的文件,则可能会导入该文件而不是名为 path
的节点模块。
¥compilerOptions.baseUrl
is resolved before node modules. This means if you have a file named ./path.js
in the project, it may 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 for config files
如果你想对 webpack.config.js、metro.config.js 或 app.config.js 等配置文件使用 TypeScript,则需要进行额外的设置。你可以利用 ts-node
需要钩子 在 JS 配置文件中导入 TypeScript 文件,从而允许导入 TypeScript,同时将根文件保留为 JavaScript。
¥If you want to use TypeScript for configuration files such as webpack.config.js, metro.config.js, or app.config.js, additional setup is needed. You can utilize the ts-node
require hook to import TypeScript files within your JS config file, allowing TypeScript imports while keeping the root file as JavaScript.
-
npm install ts-node typescript --save-dev
-
yarn add -D ts-node typescript
安装
@expo/webpack-config
软件包。¥Install the
@expo/webpack-config
package.
require('ts-node/register');
module.exports = require('./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;
};
require('ts-node/register');
module.exports = require('./metro.config.ts');
import { getDefaultConfig } from 'expo/metro-config';
const config = getDefaultConfig(__dirname);
module.exports = config;
默认支持 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:
import 'ts-node/register'; // Add this to import TypeScript files
import { ExpoConfig } from 'expo/config';
// In SDK 46 and lower, use the following import instead:
// import { ExpoConfig } from '@expo/config-types';
const config: ExpoConfig = {
name: 'my-app',
slug: 'my-app',
};
export default config;
¥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.