anmonteiro Code ramblings

ClojureScript `require` now supports `:rename`

There exist a number of differences between Clojure and ClojureScript, especially concerning namespace declarations and require specifications. Some of these differences have recently been addressed with the introduction of Clojure namespace aliasing (JIRA ticket) and implicit macro loading. A further upcoming enhancement introduces the possibility to :rename referred symbols in dependency specifications.

Starting with the next version of Clojurescript, we’ll be able to use the :rename option when requiring dependencies. As with Clojure, :rename can be used under :require, :use and :refer-clojure. The following examples take us through the basics of how using :rename looks like in practice.

  • In require specifications, we can :rename referred symbols:
cljs.user=> (require '[clojure.set :refer [intersection]
       #_=>                        :rename {intersection foo}])
nil
cljs.user=> (foo #{1 2} #{2 3})
#{2}
  • Such is the case with :use. It is possible to :rename symbols referred with :only:
cljs.user=> (ns foo.core
       #_=>   (:use [clojure.string :only [lower-case]
       #_=>                         :rename {lower-case lc}]))
nil
foo.core=> (lc "FOO")
"foo"
  • In :refer-clojure, :rename can be used with or without :excludes:
cljs.user=> (ns foo.core
      #_ =>   (:refer-clojure :rename {map core-map}))
nil
foo.core=> (core-map inc [1 2 3])
(2 3 4)

At the time of this writing, this enhancement is currently unreleased. However, you can try it out in two ways:

  1. build the ClojureScript compiler from master, or

  2. build the Planck bootstrapped REPL — Mike Fikes has promptly updated the repository to use the ClojureScript commit that includes support for :rename.

Note: This feature is now part of ClojureScript releases since version 1.9.183.

Parting thoughts

While there will always exist differences between Clojure and ClojureScript, this enhancement further narrows that gap and eases code portability between the two platforms.

Thanks for reading!