Where in the clojurescript library can I access a function to compile snippets of clojure into js?
I need this to run in the clojure (not clojurescript) repl:
(->js '(fn [x y] (+ x y)))
=> "function(x,y){return x+y}"
(require '[cljs.analyzer.api :refer [analyze empty-env]])
(require '[cljs.compiler.api :refer [emit]])
(let [ast (analyze (empty-env) '(defn plus [a b] (+ a b)))]
(emit ast))
;; result
"cljs.user.plus = (function cljs$user$plus(a,b){\nreturn (a + b);\n});\n"
(require '[cljs.js :refer [empty-state compile-str]])
(compile-str (empty-state) "(defn add [x y] (+ x y))" #(println (:value %)))
;; Output (manually formatted for easier reading)
cljs.user.add = (function cljs$user$add(x,y){
return (x + y);
});
compile-str
takes a callback as the last argument. It will be called with a map either with a key :value
containing result JS as a string or :error
with the compilation error.
In both cases org.clojure/tools.reader
is needed on your classpath.
there is a lightweight alternative: https://github.com/kriyative/clojurejs which creates the right output asked by the question.
Examples can be seen here: https://github.com/kriyative/clojurejs/wiki/Examples
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With