简体   繁体   English

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

[英]compiling snippets of clojure(script) into javascript

Where in the clojurescript library can I access a function to compile snippets of clojure into js? 在clojurescript库中我可以访问一个函数来编译clojure的片段到js?

I need this to run in the clojure (not clojurescript) repl: 我需要这个在clojure (而不是clojurescript)repl中运行:

(->js '(fn [x y] (+ x y)))
=> "function(x,y){return x+y}" 

Snippet compilation from Clojure REPL 来自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: 来自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. compile-str将回调作为最后一个参数。 It will be called with a map either with a key :value containing result JS as a string or :error with the compilation error. 它将使用带有键的映射调用:value包含结果JS作为字符串的值或:error带有编译错误的错误。

In both cases org.clojure/tools.reader is needed on your classpath. 在这两种情况下,类路径都需要org.clojure/tools.reader

there is a lightweight alternative: https://github.com/kriyative/clojurejs which creates the right output asked by the question. 有一个轻量级的替代品: https//github.com/kriyative/clojurejs ,它可以创建问题所要求的正确输出。

Examples can be seen here: https://github.com/kriyative/clojurejs/wiki/Examples 可以在这里看到示例: https//github.com/kriyative/clojurejs/wiki/Examples

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM