Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compiling snippets of clojure(script) into javascript

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}" 
like image 447
zcaudate Avatar asked Mar 13 '23 18:03

zcaudate


2 Answers

Snippet compilation from Clojure REPL

(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"

Snippet compilation from ClojureScript REPL:

(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.

like image 112
Piotrek Bzdyl Avatar answered Mar 20 '23 15:03

Piotrek Bzdyl


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

like image 23
zcaudate Avatar answered Mar 20 '23 15:03

zcaudate