将clojure(脚本)的片段编译成javascript

zca*_*ate 4 clojure clojurescript

在clojurescript库中我可以访问一个函数来编译clojure的片段到js?

我需要这个在clojure(而不是clojurescript)repl中运行:

(->js '(fn [x y] (+ x y)))
=> "function(x,y){return x+y}" 
Run Code Online (Sandbox Code Playgroud)

Pio*_*dyl 5

来自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"
Run Code Online (Sandbox Code Playgroud)

来自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);
});
Run Code Online (Sandbox Code Playgroud)

compile-str将回调作为最后一个参数.它将使用带有:value包含结果JS作为字符串的键或:error带有编译错误的键来调用.

在这两种情况下org.clojure/tools.reader都需要在类路径上.