Question

I am having a little difficulty seeing how this is done. How is it able to convert it to JS without writing any JS (everything is in Clojure or CS).

Can someone give a simple example of how the compiler would convert something simple to javascript. Maybe (def x "foo") or (defn [x] (+ x x))?

Was it helpful?

Solution

Emitting JavaScript is handled by the cljs.compiler namespace. (The link is to the source on the master branch.) As you can see, it boils down to printing strings to files.

Which strings exactly depends on the ClojureScript source, of course, but not directly: the original source is first transformed into a different representation more useful during the compilation process. This happens in the cljs.analyzer namespace.

The analyser is rather more involved then the compiler. For your (def x "foo") example, it would produce a fairly simple map which would be handled by the :def method of the emit multimethod of the compiler; search for defmethod emit :def. The things to note are the call to munge (transforming ClojureScript identifiers into valid JavaScript identifiers; e.g. foo-bar -> foo_bar) and the emits call with init as one of the arguments, where the representation of init will be generated recursively. (In this case it'll simply be "foo".)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top