5

Is there a macro for Clojure and ClojureScript that would allow you to insert different expressions depending on whether the file is being compiled in Clojure or Clojurescript?

(if-clojurescript
   (my clojurescript definition)
   (my clojure definition))

Essentially I'm looking for something like the #ifdef SOME_PLATFORM macros you might see sprinkled around C/C++ code. I think it could be useful for files that I would like to be part of a cross-over, but for which one small part of that file isn't compatible between Clojure/ClojureScript.

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
Rob Lachlan
  • 14,289
  • 5
  • 49
  • 99

4 Answers4

4

This is a new feature from Clojure 1.7 : Reader conditionals.

Also see Daniel Compton blog, for example :

#?(:clj  (Clojure expression)
   :cljs (ClojureScript expression)
   :clr  (Clojure CLR expression))

You may also want to look at macrovitch.

nha
  • 17,623
  • 13
  • 87
  • 133
3

you could check *clojure-version*

user> (if *clojure-version* "I'm Clojure" "I'm ClojureScript")
"I'm Clojure" 

cljs.user> (if *clojure-version* "I'm Clojure" "I'm ClojureScript")
"I'm ClojureScript"

This could be useful in cases where you can't split the language neutral bits into their own file (which is preferable). My personal opinion tends towards avoiding using too many of such things.

 (defmacro if-clojurescript [clj-form cljs-form]
    (if *clojure-version* clj-form cljs-form))
Arthur Ulfeldt
  • 90,827
  • 27
  • 201
  • 284
  • This looks very promising. But is there a universal way to use/require a macro? Clojurescript seems to need :use-macros, but this will raise an error in clojure. Without a language-neutral way to require a macro, I don't see how this can work. – Rob Lachlan Mar 02 '13 at 19:33
  • you can put this macro into it's own namespace, then require that naemspace from clojure files with `require` and require the same namespace from CloijureScript files with `require-macro` then both the Clojure and ClojureScript files can be closer (though still not) to language neutral. – Arthur Ulfeldt Mar 04 '13 at 18:41
3

Not really a macro, but a Leiningen plugin that produces Clojure or ClojureScript code based on a metadata annotations placed in your source: cljx

gsnewmark
  • 308
  • 1
  • 8
2

There is some stalled work called Feature Expressions to implement a general mechanism for supporting different variants of Clojure in the same codebase.

kanaka
  • 70,845
  • 23
  • 144
  • 140