Search code examples
clojureclojurescript

Clojure/ClojureScript and .cljc how they all interact together?


I am confused about the .cljc file format. I was wondering if inside a .cljc source file can Clojure and ClojureScript functions interact together. Also I was wondering if I can call from cljc to clj, cljs source file. For example if I define a function inside a .cljc source file can I call that function from the ClojureScript source file?


Solution

  • I was wondering if inside a .cljc source file can Clojure and ClojureScript functions interact together.

    Yes, that's possible and especially trivial if the common code is platform independent, for example:

    (defn my-reduce [xs]
      (reduce + xs))
    

    All of the functions and forms in the above code exist in both ClojureScript and Clojure, so you don't need to do anything extra to make it work.

    It is also possible to include platform dependent sections of code, by using 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)))
    

    In the above code, the standard reader conditional #? is used.

    if I define a function inside a .cljc source file can I call that function from the ClojureScript source file?

    Yes, absolutely, but just be careful to ensure that the code that you call doesn't include any JVM-specific code.

    In my code example, you could call to-json, from either ClojureScript or Clojure because I've been careful to isolate the platform differences inside reader conditionals.