Chapter 7. Namespaces, Libraries, and Google Closure
So far, we’ve talked mostly about basic features of the language such as syntax, semantics, and the compilation process. ClojureScript also offers compelling features at a higher structural level to facilitate code organization and sharing libraries.
In ClojureScript, as in Clojure, the highest level of code organization is namespaces, used to scope global definitions. However, despite superficial similarities, namespaces in ClojureScript are implemented completely differently than they are in Clojure because it runs in a different environment. This chapter will cover what these differences are and how to use namespaces effectively in ClojureScript.
Additionally, this chapter will describe how to create and utilize libraries. Unfortunately, one of the negative effects of ClojureScript’s reliance on the Google Closure Compiler is the fact that creating and consuming libraries is not always straightforward, particularly in light of Google Closure’s Advanced Optimizations mode.
Namespaces
To avoid name collisions, ClojureScript symbols and keywords have a
namespace component. Each *.cljs file has its own
namespace, and every REPL session has a current
namespace (cljs.user
by default). Whenever you define a
symbol using def
or one of its derivatives (such as
defn
), the namespace of the symbol is set to the current
namespace. Symbols with the same name in different namespaces are
completely different, and will not clash.
In addition to ...
Get ClojureScript: Up and Running now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.