10

I have clojurescript successfully importing macros from other namespaces. But I wonder whether a single-file construction is/should be possible with clojure 1.7, such that a macro can be defined and used. What I have tried does not work, but maybe I've missed a detail someplace.

(ns cljc.core)

#?(:cljs
(enable-console-print!))

#?(:clj
(defmacro list-macro [x y]
  `(list ~x ~y)))

(defn foo [a]
  (println (list-macro a a)))

(foo :a)

This form fails with list-macro being undefined when compiling cljs; if I remove the :clj guard around list-macro, then defmacro is undefined within the cljs compilation. Is there a way?

ben
  • 113
  • 1
  • 7
  • 3
    No. ClojureScript macros are still Clojure. They do their work compile time - when ClojureScript code is compiled to JavaScript. So they need to be compiled (from Clojure to JVM) first, before any ClojureScript compilation take place. – muhuk Apr 28 '15 at 11:31

1 Answers1

14

Yes, there is a way for a single file construction.

(ns cljc.core
  #?(:cljs (:require-macros [cljc.core :refer [list-macro]])))

#?(:clj
(defmacro list-macro [x y]
;; ...

Assumedly one of the next CLJS compiler versions will do the import automatically.

Leon Grapenthin
  • 9,246
  • 24
  • 37
  • i think that the author wants to write `defmacro`, not require – zarkone Apr 29 '15 at 04:05
  • 1
    Yes. But he needs to write `:require-macros` to use the macro in ClojureScript. This is the answer to what he asked for. – Leon Grapenthin Apr 29 '15 at 06:19
  • Clever way to force CLJ compilation first along the way! Hopefully it will indeed one day work automatically, at least when in a cljc file. – ben Apr 29 '15 at 07:50