Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save philoskim/496a01dc8d71b83c678c866874310871 to your computer and use it in GitHub Desktop.
Save philoskim/496a01dc8d71b83c678c866874310871 to your computer and use it in GitHub Desktop.
How to alias the ClojureScript namespaces in macros

How to alias the ClojureScript namespaces in macros

Problem

I wanted to alias a ClojureScript namespace in macros like this.

;; qna/very_very_long_namespace.cljs
(ns qna.very-very-long-namespace)

(defn my-add [a b]
  (+ a b))


;; qna/macros.cljc
(ns qna.macros
  #?(:cljs
     (:require [qna.very-very-long-namespace :as long])))

(defmacro my-macro [a b]
  `(long/my-add ~a ~b))

However, when I use this macro in another .cljs file like this, I have a compile warning.

;; qna/core.cljs
(ns qna.core
  (:require [qna.macros :refer-macros [my-macro]]))

(my-macro 10 20)
;; Compile Warning:
;; No such namespace: long, could not locate long.cljs, long.cljc,
;;   or JavaScript source providing "long"

I don’t have any problem when using qna.very-very-long-namespace/my-add instead of long/my-add.

;; qna/macros.cljc
(ns qna.macros
  #?(:cljs
     (:require [qna.very-very-long-namespace :as long])))

(defmacro my-macro [a b]
  `(qna.very-very-long-namespace/my-add ~a ~b))


;; qna/core.cljs
(ns qna.core
  (:require [qna.macros :refer-macros [my-macro]]))

(my-macro 10 20)
; => 30

However It is too ugly and painful to type in the very very long namespace like the above.

Solution

After a long while, I found out the way which is not very neat but works anyway.

;; qna/very_very_long_namespace.cljc    <-- Notice here!!!
;;                                          not .cljs but .cljc
(ns qna.very-very-long-namespace)

(defn my-add [a b]
  (+ a b))


;; qna/macros.cljc
(ns qna.macros
  (:require [qna.very-very-long-namespace :as long]))

(defmacro my-macro [a b]
  `(long/my-add ~a ~b))


;; qna/core.cljs
(ns qna.core
  (:require [qna.macros :refer-macros [my-macro]]))

(my-macro 10 20)
; => 30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment