将clojure(脚本)的代码段编译成javascript [英] compiling snippets of clojure(script) into javascript

查看:172
本文介绍了将clojure(脚本)的代码段编译成javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我需要这个运行在 clojure (not clojurescript)repl:

 ( - > js'(fn [xy] $ b => 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 [ab] )))]
(emit ast))

;; result
cljs.user.plus =(function cljs $ user $ plus(a,b){\\\
return(a + b); \\\
}); \\\



从ClojureScript REPL中进行代码段编译:



 (require'[cljs.js:refer [empty-state compile-str]])

(compile-str(empty-state) )#(println(:value%)))

;;输出(手动格式化以方便阅读)
cljs.user.add =(function cljs $ user $ add(x,y){
return(x + y);
}

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



在这两种情况下, org.clojure / tools.reader >

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

解决方案

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.

这篇关于将clojure(脚本)的代码段编译成javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆