4

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

6 Comments

oh awesome! thanks so much. I saw that function but didn't know about empty state. how would you define a specific namespace (instead of cljs$user)
oh hang on... my bad... I'm after the same function but for the clojure repl. slightly edited the question
@zcaudate I have updated the answer with compilation from Clojure REPL
why is it that (analyze env '(fn [a b] (+ a b))) returns ""?
I guess the comment from the code explains it clearly :): "fn statements get erased, serve no purpose and can pollute scope if named". When they are not inside a statement they are a no-op and can be ignored.
|
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.