如何在Bidi+Pushy的ClojureScript路由中添加Base URL前缀?
给Reagent/ReFrame SPA添加/myapp路由前缀(Bidi+Pushy实现)
1. 修改Bidi路由定义
把原来的根路径路由,调整为以/myapp作为顶级路径的结构:
(def routes ["/myapp" [["" :home] ;; 匹配 /myapp ["/about" :about] ;; 匹配 /myapp/about ["/contactus" :contactus]]]) ;; 匹配 /myapp/contactus
这个写法直接明确,完全贴合需求中的URL结构。
2. 调整Pushy初始化配置
创建Pushy实例时,添加:root "/myapp"选项,让Pushy自动处理路径前缀,确保路由匹配逻辑只处理前缀后的部分:
(ns your.app.routing (:require [pushy.core :as pushy] [bidi.bidi :as bidi] [re-frame.core :as rf])) (def history (pushy/pushy (fn [match] (when match (rf/dispatch [:navigate (:handler match) (:route-params match)])) (partial bidi/match-route routes) {:root "/myapp"})) ;; 指定基础路由前缀 ;; 初始化路由 (defn init! [] (pushy/start! history))
3. 生成带前缀的导航链接
使用bidi/path-for生成URL时,会自动带上/myapp前缀,直接用在Reagent组件的链接中即可:
(defn nav-bar [] [:nav [:a {:href (bidi/path-for routes :home)} "首页"] [:a {:href (bidi/path-for routes :about)} "关于页"] [:a {:href (bidi/path-for routes :contactus)} "联系页"]])
4. 配置开发服务器与静态资源
4.1 设置Base标签
在index.html的<head>中添加<base>标签,确保所有静态资源(JS、CSS、图片)的相对路径都基于/myapp/解析:
<head> <meta charset="UTF-8"> <base href="/myapp/"> <title>My App</title> </head>
4.2 开发服务器配置
- Shadow-cljs:在
shadow-cljs.edn中设置:devtools的:proxy-url,确保服务器能正确路由/myapp请求到index.html:
{:builds {:app {:target :browser ;; 其他build配置 }} :devtools {:http-root "public" :http-port 3000 :proxy-url "/myapp"}}
- Figwheel:在
project.clj的:figwheel配置中添加:server-url "/myapp":
:figwheel {:server-url "/myapp" ;; 其他figwheel配置 }
5. 测试验证
启动开发服务器后:
- 访问
localhost:3000/myapp应加载首页 - 点击导航链接应跳转至
/myapp/about、/myapp/contactus - 刷新上述路径页面,路由应能正确匹配并渲染对应组件
内容的提问来源于stack exchange,提问作者Navneet Singh
相关产品推荐
相关产品推荐

