顶层 src 目录

了解如何在 Expo Router 项目中使用顶层 src 目录。


使用 SDK 55 及更高版本的 默认模板 创建的项目已经包含一个顶层 src 目录,该目录包含 appcomponentsconstantshooks 目录。无需额外配置。

🌐 Projects created with the default template on SDK 55 and later already include a top-level src directory that contains the app, components, constants, and hooks directories. No extra configuration is needed.

如果你正在使用一个 自定义模板 或一个不包含 src 目录的现有项目,请按照以下步骤进行设置。

🌐 If you are using a custom template or an existing project that doesn't include a src directory, follow the steps below to set it up.

使用顶层 src 目录

🌐 Using a top-level src directory

1

将你的 app 目录移动到 src/app

🌐 Move your app directory to src/app.

src
app
  _layout.tsx
  index.tsx
components
  button.tsx
package.json

2

tsconfig.json 文件中更新 TypeScript 路径别名,使其指向 src 目录而不是根目录。如果你使用默认的 @/* 别名,请将其设置为 ./src/*:

🌐 Update TypeScript path aliases in the tsconfig.json file to point to the src directory instead of the root directory. If you use the default @/* alias, set it to ./src/*:

tsconfig.json
{ "compilerOptions": { "paths": { "@/*": ["./src/*"] } } }

在将应用目录移动到 src 后,这可以保持 @/ 导入的正常工作。

🌐 This keeps @/ imports working after moving your app directory into src.

3

重启你的开发服务器。

🌐 Restart your development server.

Terminal
npx expo start

# Or export for production
npx expo export

注释

🌐 Notes

  • 配置文件(app.config.tsapp.jsonpackage.jsonmetro.config.jstsconfig.json)应保留在根目录中。
  • src/app 目录的优先级高于根目录的 app。如果两者都存在,将只使用 src/app 目录。
  • public 目录应保留在根目录中。
  • 如果存在,静态渲染将自动使用 src/app 目录。
  • 你可以考虑将任何type 别名更新为指向 src 目录,而不是根目录。

自定义目录

🌐 Custom directory

警告 强烈不建议更改默认根目录。我们将不接受关于自定义根目录项目的错误报告。

你可以使用 Expo Router 配置插件危险地自定义根目录。以下操作会将根目录更改为相对于项目根的 src/routes

🌐 You can dangerously customize the root directory using the Expo Router Config Plugin. The following will change the root directory to src/routes, relative to the project root.

app.json
{ "plugins": [ [ "expo-router", { "root": "./src/routes" } ] ] }

这可能会导致意外行为。许多工具假设根目录为 appsrc/app。只有使用确切版本的 Expo CLI 的工具才会遵循配置插件。

🌐 This may lead to unexpected behavior. Many tools assume the root directory to be either app or src/app. Only tools in the exact version of Expo CLI will respect the config plugin.