Clojure/ClojureScript 和 .cljc 它们是如何交互在一起的?
Clojure/ClojureScript and .cljc how they all interact together?
我对 .cljc
文件格式感到困惑。我想知道在 .cljc
源文件中 Clojure 和 ClojureScript 函数是否可以交互。另外我想知道我是否可以从 cljc
调用到 clj
、cljs
源文件。例如,如果我在 .cljc 源文件中定义了一个函数,我可以从 ClojureScript 源文件中调用该函数吗?
I was wondering if inside a .cljc source file can Clojure and
ClojureScript functions interact together.
是的,如果通用代码是独立于平台的,那是可能的,尤其是微不足道的,例如:
(defn my-reduce [xs]
(reduce + xs))
以上代码中的所有函数和表单都存在于 ClojureScript 和 Clojure 中,因此您无需执行任何额外操作即可实现。
也可以通过使用 reader conditionals:
来包含平台相关的代码部分
(ns my-namespace.foo
(:require
[clojure.string :refer [split]]
#?(:clj [clojure.data.json :as json])))
(defn to-json [x]
#?(:cljs (clj->js x)
:clj (json/write-str x)))
在上面的代码中,使用了标准的reader条件#?
。
if I define a function inside a .cljc source file can I call that
function from the ClojureScript source file?
是的,当然可以,但要小心确保您调用的代码不包含任何特定于 JVM 的代码。
在我的代码示例中,您可以从 ClojureScript 或 Clojure 调用 to-json
,因为我已经仔细隔离 reader 条件语句中的平台差异。
我对 .cljc
文件格式感到困惑。我想知道在 .cljc
源文件中 Clojure 和 ClojureScript 函数是否可以交互。另外我想知道我是否可以从 cljc
调用到 clj
、cljs
源文件。例如,如果我在 .cljc 源文件中定义了一个函数,我可以从 ClojureScript 源文件中调用该函数吗?
I was wondering if inside a .cljc source file can Clojure and ClojureScript functions interact together.
是的,如果通用代码是独立于平台的,那是可能的,尤其是微不足道的,例如:
(defn my-reduce [xs]
(reduce + xs))
以上代码中的所有函数和表单都存在于 ClojureScript 和 Clojure 中,因此您无需执行任何额外操作即可实现。
也可以通过使用 reader conditionals:
来包含平台相关的代码部分(ns my-namespace.foo
(:require
[clojure.string :refer [split]]
#?(:clj [clojure.data.json :as json])))
(defn to-json [x]
#?(:cljs (clj->js x)
:clj (json/write-str x)))
在上面的代码中,使用了标准的reader条件#?
。
if I define a function inside a .cljc source file can I call that function from the ClojureScript source file?
是的,当然可以,但要小心确保您调用的代码不包含任何特定于 JVM 的代码。
在我的代码示例中,您可以从 ClojureScript 或 Clojure 调用 to-json
,因为我已经仔细隔离 reader 条件语句中的平台差异。