How to import macros from other libraries into yours in ClojureScript?

I have a library (say mylib) that I always use with core.match/match and have been writing like as follows:

(ns new.work.space
  (:require [clojure.core.match :refer-macros [match]]
            [mylib.core :as mylib]))

This has become so repetitive that I now want to require just my own library namespace and call core.match/match through it. So I tried wrapping the core.match macro in my own macro like this:

;; mylib.core.clj
(ns mylib.core
  (:require [clojure.core.match :as core.match]))

(defmacro match [& args]
  (list* 'core.match/match args))

;; mylib.core.cljs
(ns mylib.core
  (:require-macros [mylib.core :refer [match]]))

And I got the following error:

Uncaught TypeError: Right-hand side of 'instanceof' is not an object

at the point where mylib.core/match was called.

Can anybody help me out?

Edit: Fixed the typo in my question.

must be typo…

what’s the implementation of match?

You probably want (apply list* ...)

Edit: Oops, it’s list*, not list

Sorry. The typo exists only in my question here and not in my actual code. I fixed my question.

I’m simply wrapping clojure.core.match/match (cljs.core.match/match) in a macro that has the same name and signature so that I don’t need to require clojure.core.match everytime I use my library.

The macroexpansion works as expected in clojure REPL. So I’m guessing there is something to do with how macros are created in ClojureScript.

(require '[clojure.core.match :as core.match])

;; target
(core.match/match :x :x "success")
;;=> "success"

(defmacro match [& args]
  (list* 'core.match/match args))

(macroexpand-1 '(match :x :x "success"))
;;=> (core.match/match :x :x "success")

;; It works in Clojure REPL.
(match :x :x "success")
;;=> "success"

Did you define your macro in a .clj file?

Also, this might help: How to define and use a macro in both CLJ and CLJS?

It definitely seems like writing CLJS macros is a bit of a dark art.

Hum…

Also what you’re doing in your macro is weird. Can you use the back tick instead like:

(defmacro match [& args]
  `(core.match/match ~@args))

Yes, I define the macro in mylib.core.clj and require-macros and refer it in mylib.core.cljs.

I just rewrote the macro as you suggested but I still get the same error message.

guess we need a minimal example that could reproduce the error.

Hi, I just reproduced the error.

Not sure about the problem, but I managed to modify the code and run in shadow-cljs… https://github.com/chenyong/mylib/tree/shadow-cljs/src/mylib

I’m confused? You don’t get the error when you eval the last assert in mylib/core.cljs?

No. It runs without throwing exceptions. But I changed your code structure quite a bit. And the compiler is different now from figwheel to shadow-cljs…

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.