如何将Expo React Native Web应用部署到服务器子文件夹
解决Expo Web部署到子文件夹的路由跳转问题
问题描述
使用Expo的create-expo-app模板开发跨端应用(支持原生+Web),部署到服务器子文件夹时出现路由异常:
- 执行
npx expo build:web构建后上传,访问https://<myserver>/subfolder显示“This screen doesn't exist” - 点击“Go to home screen!”链接后,URL会丢失
subfolder前缀,虽然应用能运行,但URL不符合预期 - 已在
package.json中添加"homepage": "/subfolder",但React Navigation的NavigationContainer不像BrowserRouter那样支持直接设置basename
解决方案
通过配置NavigationContainer的linking属性,为路由添加子文件夹前缀,具体步骤如下:
- 确保依赖完整
如果项目未安装@react-navigation/web,执行安装命令:
npm install @react-navigation/web
- 配置NavigationContainer的linking属性
在应用的根导航组件中,给NavigationContainer添加linking配置,指定路由前缀和页面映射:
import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; const Stack = createNativeStackNavigator(); export default function App() { return ( <NavigationContainer linking={{ enabled: true, // 配置生产和开发环境的路由前缀 prefixes: [ 'https://<myserver>/subfolder', 'http://localhost:3000/subfolder', ], // 页面路径映射,将子文件夹根路径对应到Home页面 config: { screens: { Home: '', // 空字符串对应子文件夹的根路径 // 其他页面示例:About: 'about' 对应 /subfolder/about // About: 'about', }, }, }} > <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} /> {/* 其他页面组件 */} {/* <Stack.Screen name="About" component={AboutScreen} /> */} </Stack.Navigator> </NavigationContainer> ); }
- 重新构建并部署
执行构建命令重新生成Web资源:
npx expo build:web
将web-build文件夹上传到服务器的subfolder目录即可。
验证方法
按照复现步骤测试:
- 运行
create-expo-app初始化项目 - 在
package.json中设置"homepage": "/web-build/" - 配置上述
NavigationContainer的linking属性,prefixes改为['http://localhost:port/web-build/'] - 执行
npx expo export:web生成web-build文件夹 - 启动本地服务器(如
npx serve或py -m http.server),访问http://localhost:port/web-build/,此时应直接显示Home页面,跳转链接也会保留web-build前缀。
内容的提问来源于stack exchange,提问作者Byron
相关产品推荐
相关产品推荐

