estolua
estolua

Reputation: 676

Import Record Type in Clojure/ClojureScript

Is there any way to import a record type, that works in Clojure as well as ClojureScript? As far as I can tell it's (ns x (:import y [A B])) for Clojure, (ns x (:require y :refer [A B])) for ClojureScript, and each is invalid for the respective other.

Upvotes: 0

Views: 743

Answers (1)

Daniel Compton
Daniel Compton

Reputation: 14569

Ignoring the specifics on the syntax of requiring records, there are two main ways to write ns declarations (or any platform specific code) for multiple Clojure variants while sharing the majority of your code.

  1. CLJX is a Clojure preprocessor that runs before the Clojure compiler. You write platform specific code prefixed with #+clj or #+cljs in a .cljx file. It can run on pretty much any Clojure code, and will spit out multiple platform specific files which the respective Clojure Compilers can handle.

  2. Reader Conditionals are a feature in Clojure 1.7 and are available in recent releases of ClojureScript. This is similar in spirit to cljx, but is integrated into the Clojure Compiler. You write code with reader conditionals like #?(:clj 1 :cljs 2) in files with a .cljc extension.

Now back to your specific question, you can achieve this with Reader Conditionals like so:

(ns myapp.music-store
  (:require #?(:clj [myapp.cool-music]
               :cljs [myapp.cool-music :refer [Vinyl]]))
  #?(:clj
     (:import [myapp.cool_music Vinyl])))

I wrote a longer blog post about this too: Requiring records in Clojure and ClojureScript

Upvotes: 2

Related Questions