hello, I am new to figwheel/clojurescript, though I have a background in FP. I have a web app running on figwheel-main and I’d like to read a JSON file into ClojureScript. what’s the best way to do that? I found https://clojureverse.org/t/using-none-code-resources-in-cljs-builds/3745 for shadow-cljs, is there an analog in Figwheel? If not, what’s the simplest way to do this? I am open to putting it into a JS file as an object and reading it from there but I don’t know how
Is the JSON file for your app or to configure figwheel-main?
It’s for my app, it’s test/development data
Cool. My approach has been to write a macro which reads in the file. For example, I have a markdown file which I read in, transform to hiccup and then render in my app. I do a similar thing with SVG files.
Got it, so I can basically copy the macro from shadow-cljs then? tbh I am new to Clojure and have never actually written a macro
Yep. For sure. You can even configure your macro to run when you make changes to your JSON file 🙂
It would also take me about 15-20 minutes to move my code to shadow-cljs tbh - probably less time than to copy and test the macro laughcry
tried my best and spent the whole evening on this but couldn't get the macro to work 😞
What does the code look like? What issues are you running into?
Making a note to respond tonight - this stuff is on my private machine at home and I am at work
This is my code:
(ns nim.slurp (:require [ :as io]
[clojure.string :as str]
[cljs.env :as env])
(:import [java.nio.file Paths]
[ File]))
(def normalize-name
(if (= File/separatorChar \/)
identity
(fn [^String name]
(str/replace name File/separatorChar \/))))
(defn ns->path [name]
(-> name
(str)
(str/replace #"\." "/")
(str/replace #"-" "_")))
(defn ns->cljs-filename [name]
(-> name
(ns->path)
(str ".cljs")))
(defn slurp-resource [environment path]
(let [current-ns (-> environment :ns :name)
path (let [parent (-> (Paths/get current-ns (into-array String []))
(.getParent))]
(when-not parent
(throw (Exception. (str "Could not resolve path " path " from " current-ns))))
(-> parent
(.resolve path)
(.normalize)
(.toString)
(normalize-name)))
rc (io/resource path)]
(when-not rc
(throw (.Exception "Could not resolve RC")))
(slurp rc)))
(defmacro inline
[path]
(when-not (string? path)
(throw (.Exception (str "shadow.resource/inline must be called with a literal string argument"))))
(slurp-resource &env path))
when I load the file I get
clj꞉nim.slurp꞉>
; Evaluating file: slurp.clj
; Unexpected error (NullPointerException) macroexpanding inline at (slurp.clj:46:1).
; null
Frankly I think this is a bit too much for me at this stage of learning ClojureScript. I'd rather switch to shadow-cljs and use the built in functionalityWhat does your call-site look like?