顶层 src 目录

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


随着你的项目增长,将所有包含应用代码的目录移动到一个单独的 src 目录中可能会很有帮助。Expo Router 开箱即支持这一点。

🌐 As your project grows, it can be helpful to move all the directories containing application code into a single src directory. Expo Router supports this out of the box.

使用顶层 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.