Hello World - Clojurescript - clojure

Beginner here.
Can I compile an existing Clojure script to run it on the web using ClojureScript?
Let's say that I have a script that prints Hello world in my terminal, and I want to print that text on the browser. Should I rewrite a whole script with ClojureScript syntax, or should I just compile it using another compiler?
(ns clojure-hello-world.core
(:gen-class))
(defn -main [& args]
(println "Hello World"))

(Long answer :P)
Even though Clojure and ClojureScript share a good amount of features, there are some that are specific to one or the other. For example there are no real classes in JavaScript so the :gen-class specification in the ns form doesn't make much sense.
One important fact is that the syntax of both Clojure and ClojureScript is exactly the same, differences have to do mostly with the host VM in which they run (Java VM in the case of Clojure and JavaScript VM in the case of ClojureScript).
There is a list of the differences between the two Clojure implementations here.
There's also a tool called cljx to "write a portable codebase targeting Clojure/ClojureScript". Recently there has been some discussion on the Clojure Dev group around finally implementing feature expressions which would on one hand deprecate the use of cljx but on the other complicate the work that tools have to do to extract information from Clojure source files.

I would start with lein-cljsbuild to get started. This will get you going with a nice edit eval and look at browser loop. It's well worth getting this setup first because it makes learning ClojureScript much more fun. I promise it's worth the hassle. If you need more interactive support the folks in #clojure on freenode are very kind and helpful.

Basically, the Browser executes JavaScript. You compile your ClojureScript code to JavaScript. The Browser loads your JavaScript via an HTML page. So, you have to create an HTML Page and point your Browser at it.
The simplest way I got started was to use Luminous (http://www.luminusweb.net/docs/clojurescript.md).
However, Chestnut (https://github.com/plexus/chestnut) looks promising.

Related

Turn hiccup into html in a reagent application

This might sound a stupid question, but how do I turn a piece of hiccup into html in a ClojureScript reagent application?
I want something like this :
(html [:div [:p "hello world" ]])
that produces
<div><p>hello world</p></div>
This is what you can do in hiccup.core, but as far as I can see, that's in Clojure. Not ClojureScript in the browser.
OTOH, ClojureScript / Reagent clearly knows how to do it in the browser. It's doing it all the time. But I can't actually find a library call anywhere in reagent where I can do this explicitly, outside the reagent rendering process.
I'm not sure why you would want to do this, but it appears one answer is to use the function:
reagent.dom.server/render-to-string
Normally, your Reagent components only return Hiccup data, and you let reagent.dom/render do all the hard work of reactively "rendering" only the changed components into the DOM.
P.S. When in doubt, you can often find documentation at cljdoc.org. Most Clojure projects have a direct link there from their GitHub page (Reagent does, for example). Or, you can go to cljdoc.org directly and search there.

Can I create a program in Clojure able to edit it's own code?

I am thinking of creating an educational program in Clojure that would show a console where the user could edit code in order to change a running code in another part of the screen (like a game, for instance). Would that be possible? If so, what should I study in order to be able to do this?
It is possible. See this Interactive programming Flappy Bird in ClojureScript . It uses clojurescript and figwheel as its development environment.
The awesome thing about figwheel is that you can change the flappybird running code in the browser by simply evaluating new code in the repl and then figwheel push the new code to the browser. The changes happened in real time.
You can start studying clojure and clojurescript.
Hm, changing code during runtime is one of the basic concepts behind clojure.
Watch this for more on this topic: https://www.youtube.com/watch?v=P76Vbsk_3J0
Otherwise every repl or form of a repl can do that.
To get started have a look at Lighttable: http://lighttable.com/ It has inline evaluation in the editor.

Clojure Worksheets

I have been learning Clojure a bit recently. Is there such a thing in Clojure world as Scala-like worksheets, into which I can put any code and get it evaluated as soon as I save it? Or maybe there's a similar solution for Clojure?
I am now working with lein repl and, sadly, can't say it's the most usable tool ever.
In Lisp development in general (and Clojure in particular) the preferred programming style is what's usually dubbed interactive programming - the developer keeps an image of the app loaded at all times and interacts with it via a REPL. You can easily modify the loaded code on the fly and test changes immediately in the REPL (that's not easy at all with Scala - one has to resort to something like JRebel to do it). I find the Scala worksheets a pretty primitive solution in comparison...
The workflow that I follow in Clojure is:
I open nREPL.el in Emacs - this loads my lein2 project with all of its dependencies and gives me a REPL which I can use the try out stuff
I write some code in source code and load the changed functions (maybe by evaluating a top level form with C-M-x
Afterwards I'd press C-x C-z to jump back to the REPL and I try out the new code in it
I go back to step 2
Basically the Clojure REPL is much more powerful than the Scala REPL and I personally consider it hugely superior to the Scala IDE worksheets. Once you get used to the interactive incremental style of programming Lisp offers everything else starts to look strangely complex by comparison. I'm not familiar with Eclipse's CounterClockWise Clojure plugin, but I'm pretty sure it offers similar functionality to Emacs's nREPL.el.
You might want to take a look at the autoexpect plugin for Leiningen. Every time you save any file in the working directory, the plugin compiles and runs your code; as a bonus, it will evaluate any "expect" function calls which can serve as tests. This is very helpful for test driven development and is a nice compliment to working with the REPL as described in the other answer (I often use one or the other or both together depending on how many test cases I have in place).
I should note that running autoexpect is far faster than running "lein test" or "lein run" repeatedly, due to the startup cost of the JVM and Leiningen.
It sounds like what you are looking for is the Clojure Koan plugin. This a worksheet-style problem-solving exercise tool that watches your edits and provides instant feedback on the correctness of your work.
For actual development workflow I second the advice others here have provided on tooling and interactive environment setup, but since you specifically said you are learning Clojure, this can be a fun approach. There is also a web application called 4Clojure that you might have fun playing with.
However you will eventually (or right away) want to get a smooth and convenient development environment set up, and I haven't seen any mention so far of a few important tools. One person mentioned Nrepl. If you like Emacs, there's a slime/swank-like interaction mode that jacks into nrepl called nrepl.el that provides very nice integration between editing files and messing around in the repl. Similarly there is VimClojure, and you can find plugins for IntelliJ (LaClojure) and Eclipse (Counterclockwise) that are also popular and well-maintained.
Someone mentioned autoexpect. If you are looking for a good TDD setup, I would recommend midje. If you are using a 2.0 preview release of leiningen there are a few issues with the lazytest integration being in flux, and lazytest itself is or should be deprecated. But I prefer midje over expectations, personally, and these problems will surely be worked out in the 2.0 release of lein-midje. The stable version of lein-midje that works with the non-preview (1.x) leiningen has autotest-like functionality using lazytest.
As nobody has mentioned it, cursive is really nice these days, although I was sad to move back to a full blown IDE. You can easily do the same thing as Emacs with the built in repl, just move into the namespace that you are working with and synchronise every time you make changes. It's a really nice way of working.

Get the Clojurescript repl/connect to not compile when in production?

In my clojurescript code I have the following:
(defn onload [] (repl/connect "http://localhost:9000/repl"))
(set! (.-onload js/window) onload)
The Clojurescript repl is very useful in development, but I am hesitant to leave it in the code during production. What is the cleanest way to have the above code present during development (simple compilation), but absent during production (advanced compilation)?
The modern-cljs tutorial actually describes exactly how to solve this here.
Hope that helps!
Unfortunately there aren't currently any well defined ways to do conditional compilation in ClojureScript.
You could add configuration variables to control whether to start a REPL in a variety of ways, but one quick and easy way would be to get the hostname of the current page, and only invoke repl/connnect if it was "localhost" or whatever other domains you're using for development work.
I think a combination of lein2 profiles and cljsbuild src-paths munging can do the trick. eg, create a namespace that simply loads your repl, and exclude it with a profile run for the final compile (possibly might need to create a dummy namespace in another src-path directory).

webjure vs compojure?

I've heard of two Clojure based web application frameworks: Webjure and Compojure. Can someone let me know which is better?
Now you can add Ring to the list. All of these frameworks are very new and likely to evolve (or die) quickly, but Compojure does seem to be the most actively developed based on the past 6 months or so.
"Better" is too subjective a question to get a definitive answer to. Try them all and see what works.
Compojure has been working very well for me so far. I like the simplicity of the design, the flexibility and the fact that it encourages a nice idiomatic functional style.
Sample server:
(use 'compojure)
(defroutes my-app
(GET "/index.html"
(html
[:h1 "Hello World!!"]
[:body "This is some text"]))
(ANY "*"
[404 "Page not found"]))
(run-server {:port 80}
"/*" (servlet my-app))
Note that Compojure uses Ring internally.
I second Rayne's recommendation on Moustache.
Right now, we are using Ring (base layer, middleware), Moustache (routing), Hiccup (html generation). We just began using Compass for CSS (http://compass-style.org/). So far, I'm happy with this collection of small libraries rather than a big "complete stack" framework (Django, Rails, ect...).
Now, there is also a new one named Noir build on top of compojure. Really recommended, especially with Heroku.
Compojure seems to be getting the most buzz right now. Not necessarily indicative of quality, but the one with the most eyes will probably evolve the fastest.
There is also Moustache, which is what I use in TryClojure, along with Ring. It's pretty awesome.
Compojure is based on Ring, which is a low-level framework that doesn't attempt to hide much of HTTP. It's similar to WSGI (Python) or Rack (Ruby). Ring has a concept of middleware, small pieces of code that can do something meaningful with an HTTP request and/or response, such as dump header infos, manage cookies etc. Compojure is a higher-level framework, somewhat similar to Ruby's Sinatra. Its aim is to provide a convenient API (or DSL, if you prefer) for most tasks a Web app developer faces. It's usually used together with an HTML generation library, such as Hiccup.
I haven't heard much about Webjure in the last few months, I'm not sure it's in active development (but I'd be interested to find out more). It precedes Ring, AFAICT, which seems to have become somewhat of a standard for Clojure Web frameworks.
I've been building a project for my own use using Compojure and it has worked out great. It doesn't really get in the way very much and lets you focus on what's important, your problem domain. The project is about 1100 lines of clojure just to give you an idea of the size.