compiling snippets of clojure(script) into javascript

守給你的承諾、 提交于 2019-12-06 06:08:36

问题


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

回答1:


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.




回答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



来源:https://stackoverflow.com/questions/36300173/compiling-snippets-of-clojurescript-into-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!