Figwheel启用:ring-handler无法加载test.core/handler命名空间如何解决
问题根因
报错是三个配置和代码错误共同导致的:
:ring-handler配置未使用变量引用,且test.core命名空间缺少必要依赖,导致Figwheel无法正常加载handler所在命名空间- ClojureScript编译配置的入口命名空间写错,指向了服务端Clojure命名空间而非客户端入口
- 自定义handler拦截了所有非根路径请求,会阻断Figwheel热更新通信、静态资源加载的内置逻辑
修正步骤
1. 补全依赖、修正project.clj配置
首先补上缺失的compojure依赖,修正两处错误配置:
:ring-handler使用var引用写法#'test.core/handler,既可以让Figwheel正确识别handler变量,也支持服务端代码热加载- 将ClojureScript编译的
:main入口从服务端命名空间test.core改为客户端入口test.client
修正后的完整project.clj如下:
(defproject test-ring-handler "0.1.2-SNAPSHOT" :min-lein-version "2.0.0" :description "test-ring-handler" :license {:name "GNU GPL v3+" :url "http://www.gnu.org/licenses/gpl-3.0.en.html"} :dependencies [[org.clojure/clojure "1.11.1"] [org.clojure/clojurescript "1.11.54"] [reagent "1.1.1"] [cljsjs/react "18.0.0-rc.0-0"] [cljsjs/react-dom "18.0.0-rc.0-0"] [ring "1.9.5"] [ring/ring-core "1.9.5"] [compojure "1.7.0"] ;; 补上缺失的compojure依赖 [figwheel "0.5.20"] ] :plugins [[lein-cljsbuild "1.1.7"] [lein-figwheel "0.5.19"] ] :resource-paths ["resources" "target"] :clean-targets ^{:protect false} [:target-path] :profiles {:dev {:cljsbuild {:builds {:client {:figwheel {:on-jsload "test.client/run"} :compiler {:main "test.client" :optimizations :none}}}}}} :figwheel {:repl false :ring-handler #'test.core/handler ;; 用var引用指向自定义handler } :cljsbuild {:builds {:client {:source-paths ["src"] :compiler {:output-dir "target/public/client" :asset-path "client" :output-to "target/public/client.js" :main "test.client" ;; 修正为客户端入口命名空间 }}}} )
2. 修正服务端handler逻辑
不要直接拦截所有请求返回404,自定义路由匹配不到时返回nil,Figwheel会自动接管静态资源、热更新websocket等内置请求的处理。修正后的src/test/core.clj如下:
(ns test.core (:use compojure.core) (:require [ring.adapter.jetty :as jetty] [compojure.route :as route] [clojure.data.json :as json])) (def home "<!DOCTYPE html> <html> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\"> <link rel=\"icon\" href=\"https://clojurescript.org/images/cljs-logo-icon-32.png\"> </head> <body> <div id=\"container\"></div> <script src=\"/client.js\" type=\"text/javascript\"></script> </body> </html>") ;; 自定义路由,可按需添加REST API接口 (defroutes app-routes (GET "/" [] {:status 200 :headers {"Content-Type" "text/html"} :body home}) ;; 示例API接口可直接在此添加 ;; (GET "/api/test" [] {:status 200 :body (json/write-str {:code 0 :data "ok"})}) ) (defn handler [request] (app-routes request))
3. 重启验证
执行以下命令清理缓存后启动Figwheel即可正常运行:
lein clean lein figwheel
启动后访问Figwheel默认地址http://localhost:3449即可看到Reagent渲染的页面,热更新、自定义REST接口均可正常工作。
内容的提问来源于stack exchange,提问作者Francois
相关产品推荐
相关产品推荐

