将 clojure(script) 片段编译成 javascript
compiling snippets of clojure(script) into javascript
我可以在 clojurescript 库的哪个位置访问将 clojure 片段编译成 js 的函数?
我需要这个 运行 在 clojure(不是 clojurescript)repl:
(->js '(fn [x y] (+ x y)))
=> "function(x,y){return x+y}"
来自 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"
来自 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
将回调作为最后一个参数。它将使用包含结果 JS 作为字符串的键 :value
或带有编译错误的 :error
的映射调用。
在这两种情况下,您的类路径中都需要 org.clojure/tools.reader
。
有一个轻量级的替代方案:https://github.com/kriyative/clojurejs 可以创建问题所要求的正确输出。
例子可以在这里看到:https://github.com/kriyative/clojurejs/wiki/Examples
我可以在 clojurescript 库的哪个位置访问将 clojure 片段编译成 js 的函数?
我需要这个 运行 在 clojure(不是 clojurescript)repl:
(->js '(fn [x y] (+ x y)))
=> "function(x,y){return x+y}"
来自 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"
来自 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
将回调作为最后一个参数。它将使用包含结果 JS 作为字符串的键 :value
或带有编译错误的 :error
的映射调用。
在这两种情况下,您的类路径中都需要 org.clojure/tools.reader
。
有一个轻量级的替代方案:https://github.com/kriyative/clojurejs 可以创建问题所要求的正确输出。
例子可以在这里看到:https://github.com/kriyative/clojurejs/wiki/Examples